Probably this won't help you much, but you could definitely use Regex (all white considering your context).
Here is code I used in one of my projects.
def pretty_json(data):
"""
With the power of regex, remove the annoying \n inside an array in `le Jeson`
Our input (json output) looks like this:
{
| "num_nodes": 8,
| "adjacency_matrix": [
| [
| "",
| "H",
| ],
| [
| "E",
| 0,
| ]
| ],
| "adjacency_list": {
| | "H": [
| | {
| | "node": "F",
| | "weight": 1
| | },
| | {
| | "node": "G",
| | "weight": 1
| | }
| | ],
| }
}
We'll turn this boi into something more readable
"""
# define the necessary matches
SBRACKET = r'\[\n\s+"'
CBRACKET = r'\{\n\s+'
C_INSIDE = r'",\n\s+'
C_INSIDE_LF = r'(")\n\s+\]'
D_INSIDEARR = r'(\d,)\n\s+'
D_INSIDEARR_LF = r'(\d)\n\s+\]'
D_INSIDEOBJ_LF = r'(\d)\n\s+\}'
# replace all occurrences
data = re.sub(SBRACKET, '[ "', data)
data = re.sub(C_INSIDE, '", ', data)
data = re.sub(D_INSIDEARR, r'\1 ', data)
data = re.sub(D_INSIDEARR_LF, r'\1 ]', data)
data = re.sub(C_INSIDE_LF, r'\1 ]', data)
data = re.sub(CBRACKET, '{ ', data)
data = re.sub(D_INSIDEOBJ_LF, r'\1 }', data)
return data
Data generated by it (Not perfect)
{ "num_nodes": 8, "adjacency_matrix": [
[ "", "S7", "S5", "S3", "S4", "S6", "S8", "S2", "S1" ],
[ "S7", 0, 0, 0, 1, 1, 1, 0, 0 ],
[ "S5", 0, 0, 1, 0, 1, 0, 1, 1 ],
[ "S3", 0, 1, 0, 0, 1, 0, 0, 1 ],
[ "S4", 1, 0, 0, 0, 1, 0, 1, 0 ],
[ "S6", 1, 1, 1, 1, 0, 1, 0, 0 ],
[ "S8", 1, 0, 0, 0, 1, 0, 0, 0 ],
[ "S2", 0, 1, 0, 1, 0, 0, 0, 1 ],
[ "S1", 0, 1, 1, 0, 0, 0, 1, 0 ]
],
"adjacency_list": { "S7": [
{ "node": "S8", "weight": 1 },
{ "node": "S4", "weight": 1 },
{ "node": "S6", "weight": 1 }
],
"S5": [
{ "node": "S1", "weight": 1 },
{ "node": "S6", "weight": 1 },
{ "node": "S3", "weight": 1 },
{ "node": "S2", "weight": 1 }
],
"S3": [
{ "node": "S6", "weight": 1 },
{ "node": "S5", "weight": 1 },
{ "node": "S1", "weight": 1 }
],
"S4": [
{ "node": "S7", "weight": 1 },
{ "node": "S6", "weight": 1 },
{ "node": "S2", "weight": 1 }
],
"S6": [
{ "node": "S8", "weight": 1 },
{ "node": "S4", "weight": 1 }
],
"S8": [
{ "node": "S6", "weight": 1 },
{ "node": "S7", "weight": 1 }
],
"S2": [
{ "node": "S1", "weight": 1 },
{ "node": "S5", "weight": 1 }
],
"S1": [
{ "node": "S5", "weight": 1 },
{ "node": "S3", "weight": 1 }
]
}
}
Note that you have to json.dumps() your input first with an indent argument set
indent=4?json.JSONEncoder.print(json.dumps(my_json, indent=None, separators=(",",":"))), which results in compact one-line form{"object":{"key":"value","boolean":true},"array":[1,2,3]}