How to convert multiline json to single line?

Viewed 3103

I am trying to convert a multiline json to a single line json. So the existing json file I have looks like this:

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

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)

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

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

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.
Related