I have a json which contains dictionaries, lists, integers etc.
json_str = '''
{
"name": "John",
"age": 30,
"pets": [
{
"name": "Fluffy",
"type": "cat",
"toys": [
"ball",
"string",
"box"
]
},
{
"name": "Fido",
"type": "dog",
"toys": [
"bone",
"frisbee"
]
}
]
}
'''
Currently each element inside list starts with a new line. I want list elements to start from the same line as the last element ended. The end result should look something like this -
{
"name": "John",
"age": 30,
"pets": [ {
"name": "Fluffy",
"type": "cat",
"toys": [ "ball", "string", "box" ]
}, {
"name": "Fido",
"type": "dog",
"toys": [ "bone", "frisbee" ]
} ]
}
'''
Basically I want list elements to be separated by a comma and a whitespace. I'm using python json.dumps to write json to a file and want a solution in python
I've searched through internet and chatgpt but couldn't find anything that works. I found some solution like using custom encoder in json.dumps but it doesn't work -
class ObjectEncoder(JSONEncoder):
def default(self, o):
if isinstance(o, Enum):
return o.name
if isinstance(o, list):
return ", ".join(json.dumps(i, indent=self.indent) for i in o)
## Remove all attributes which are None;
for key, value in list(o.__dict__.items()):
if value is None:
del o.__dict__[key]
return o.__dict__
The suggestion made in this answer works. You'll have to patch the whole
_make_iterencodethough (we're basically editing only a few lines in_iterencode_list):Output:
Edit: adding white spaces before/after brackets and using
mockEdit2: using standard library