Consider the following code:
>>> import json
>>> data = {
... 'x': [1, {'$special': 'a'}, 2],
... 'y': {'$special': 'b'},
... 'z': {'p': True, 'q': False}
... }
>>> print(json.dumps(data, indent=2))
{
"y": {
"$special": "b"
},
"z": {
"q": false,
"p": true
},
"x": [
1,
{
"$special": "a"
},
2
]
}
What I want is to format the JSON so that JSON objects that have only a single property '$special' are rendered on a single line, as follows.
{
"y": {"$special": "b"},
"z": {
"q": false,
"p": true
},
"x": [
1,
{"$special": "a"},
2
]
}
I have played around with implementing a custom JSONEncoder and passing that in to json.dumps as the cls argument, but the two methods on JSONEncoder each have a problem:
The
JSONEncoderdefaultmethod is called for each part ofdata, but the return value is not a raw JSON string, so there doesn't appear to be any way to adjust its formatting.The
JSONEncoderencodemethod does return a raw JSON string, but it is only called once for thedataas a whole.
Is there any way I can get JSONEncoder to do what I want?
jsonmodule is not really set up to let you control the output format to that extent, really."$special"is present, is it guaranteed to be the only key?{'$special': 'some key'}appear abundantly throughout this JSON data, so I was just exploring the possibility of visually compacting it a bit. It can be assumed that'$special'is the only key if it is present, although I suppose that is orthogonal to what I am really asking: how to locally modify JSON formatting. It might be the answer is simply "you can't with thejsonmodule."JSONEncoder. I ended up just giving up the fight and going with a standard prettify.