Home > other >  Python - Convert multiline json
Python - Convert multiline json

Time:11-24

I am trying to convert multiline json to single line json. So the existing json file I have looks like this. When I load the file, it comes in a dictionary and not sure how to strip blank spaces in the dictionary.

 f = open(test.json')
 data = json.load(f)

My json look like

 {
   "a": [
   "b",
   "bill",
   "clown",
   "circus"
],
    "vers": 1.0
}

What I would like it to come out is the following.

{"a":["b","bill","clown","circus"],"vers":1}

Any help on this would be greatly appreciated. Thanks!

CodePudding user response:

Using the standard library json you can get:

import json

with open('test.json') as handle:
    data = json.load(handle)

text = json.dumps(data, separators=(',', ':'))
print(text)

Result:

{"a":["b","bill","clown","circus"],"vers":1.0}

Remark:

  • 1.0 is not simplified to 1, probably, because this would change the type from float to int at Python level.

CodePudding user response:

You can use this library and read documents:

https://pypi.org/project/JSON_minify/

  • Related