0

I have a .json file that currently looks as so in txt editor

{"a": [1,2,3], "b":[2,3], "c":[1,3,5]}

Essentially its holding a dictionary at the moment. I was wondering if there was a way to use Python to "beautify" the .json file by adding newlines every key. Using json indent results in:

{
   "a": [
          1,2,3
        ],
   "b":[
          2,3
       ],
   "c":[
          1,3,5
       ]
}

So now I want to strip the newlines and form:

{
   "a": [1,2,3],
   "b":[2,3],
   "c":[1,3,5]
}
petezurich
  • 9,280
  • 9
  • 43
  • 57
PhantomQuest
  • 349
  • 4
  • 12

2 Answers2

0

Not very elegant, but you could use string replacing to format the json, something like:

with open('foo.json', 'r') as handle:
    parsed = json.load(handle)

string_json = json.dumps(parsed, indent=0, sort_keys=True)
string_replaced = string_json.replace("\n", "").replace("{", "{\n").replace("],", "],\n").replace("}", "\n}")

this will give your desired output, but not sure how extensible it will be, as it uses simple string matching

TurtleMayhem
  • 32
  • 1
  • 3
0

For a file data.json in the same directory as your python script

{"a": [1,2,3], "b":[2,3], "c":[1,3,5]}

You can read the original JSON and then over-write the original file with the "beautified" version.

import json
with open('data.json', 'r') as f:
    data = json.load(f)
with open('data.json', 'w') as f:
    json.dump(data, f, indent=2, sort_keys=True)

New data.json

{
  "a": [
    1, 
    2, 
    3
  ], 
  "b": [
    2, 
    3
  ], 
  "c": [
    1, 
    3, 
    5
  ]
}