Skip to content
This repository has been archived by the owner on May 9, 2021. It is now read-only.

[feature] sort json keys #16

Open
rasa opened this issue May 21, 2014 · 2 comments
Open

[feature] sort json keys #16

rasa opened this issue May 21, 2014 · 2 comments

Comments

@rasa
Copy link
Contributor

rasa commented May 21, 2014

What about standardizing our json by sorting the keys? This provides several benefits:

  1. Easily find a key... they're sorted!
  2. If we change the json programmatically, the diff will just show the change, not a huge diff
  3. It will make cut-n-pasting between files easier
  4. It will reduce merge conflicts
  5. It will reduce mistakes when manually updating a bunch of files
  6. It will make diffing two different files easier

Below is a Python script to do this. It would be easy to craft this in Ruby as well.

# jsonfmt.py
from __future__ import print_function

import json
import os
import sys

def touch(filename, mtime):
  with open(filename, 'a+'):
    pass
  os.utime(filename, (mtime, mtime))
  return 0

file = sys.argv[1]
print('Updating', file)

mtime = os.path.getmtime(file)

with open(file, 'r') as f:
  json_data = json.load(f)

new_data = json.dumps(json_data, sort_keys=True, indent=2)
with open(file, 'w') as f:
  f.write(new_data)

touch(file, mtime)

sys.exit(0)
@StefanScherer
Copy link
Contributor

What about packer fix?

packer fix template.json >xx
mv xx template.json

It seems that packer fix also sorts all keys. But you have to write a temporary file. Perhaps there is a more elegant way to do it.

@rasa
Copy link
Contributor Author

rasa commented May 26, 2014

That's another excellent reason to sort our keys. Packer may force us to, some day.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants