简体   繁体   中英

Python - Convert multiline json

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!

You can use this library and read documents:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM