I modified @Martin Gergov answer a bit to make things simpler and more JSON-friendly.
def transform(json_obj, indent=4):
def inner_transform(o):
if isinstance(o, list) or isinstance(o, tuple):
for v in o:
if isinstance(v, dict):
return [inner_transform(v) for v in o]
# elif isinstance(v, list): # check note on the bottom
# ...
return "##<{}>##".format(json.dumps(o))
elif isinstance(o, dict):
return {k: inner_transform(v) for k, v in o.items()}
return o
if isinstance(json_obj, dict):
transformed = {k: inner_transform(v) for k, v in json_obj.items()}
elif isinstance(json_obj, list) or isinstance(json_obj, tuple):
transformed = [inner_transform(v) for v in json_obj]
transformed_json = json.dumps(transformed, separators=(', ', ': '), indent=indent)
transformed_json = transformed_json.replace('"##<', "").replace('>##"', "").replace('\\"', "\"")
return transformed_json
Test it with this
data = [
[
[1,2,3],
{
"a": ["a", 'b', "c", "d"],
"b": {
"x": [1, 2, 3, None],
"y": "value"
},
"c": [1, 2, 3]
}
]
]
pretty_json = transform(data)
print(pretty_json)
Result:
[
[
[1, 2, 3],
{
"a": ["a", "b", "c", "d"],
"b": {
"x": [1, 2, 3, null],
"y": "value"
},
"c": [1, 2, 3]
}
]
]
Unless if you want a list which contains a list which contains a list+ which contains a dict like [[1,2,[2, {"a": 0}]]]
you'd have to modify that yourself...
pprint
. (Hard:) consider writing a custom JSONEncoder and pass it ascls
argument todumps
. (Obligatory:) think again why you need this all. – Cranach