Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting a JSON file by outer object name

I have a json file input.json thus:

{
   "foo":{
       "prefix":"abc",
       "body":[1,2,3]
   },
   "bar":{
       "prefix":"def",
       "body":[4,5,6]    
   }
}

I would like to sort it by the outer object names, with "bar" coming before "foo" in alphabetical order like so:

{
   "bar":{
       "prefix":"def",
       "body":[4,5,6]    
   },
   "foo":{
       "prefix":"abc",
       "body":[1,2,3]
   }
}

to produce file output.json.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Versions of this question have been asked of Java/Javascript (here and here)

Is there a way to accomplish this using a command line tool like sed/awk or boost.json?

>Solution :

Using jq, you could use the keys built-in to get the key names in sorted order and form the corresponding value object

jq 'keys[] as $k | { ($k) : .[$k] }' json

Note that jq does have a field --sort-keys option, which cannot be used here, as it internally sorts the inner level objects as well.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading