how to save multi level dict per line?

Question:

i have this dict

dd = {
    "A": {"a": {"1": "b", "2": "f"}, "z": ["z", "q"]},
    "B": {"b": {"1": "c", "2": "g"}, "z": ["x", "p"]},
    "C": {"c": {"1": "d", "2": "h"}, "z": ["y", "o"]},
     }

and i wanna have it formated in one line like this in a file i used

with open('file.json', 'w') as file: json.dump(dd, file, indent=1)
# result
{
 "A": {
  "a": {
   "1": "b",
   "2": "f"
  },
  "z": [
   "z",
   "q"
  ]
 },
 "B": {
  "b": {
   "1": "c",
   "2": "g"
  },
  "z": [
   "x",
   "p"
  ]
 },
 "C": {
  "c": {
   "1": "d",
   "2": "h"
  },
  "z": [
   "y",
   "o"
  ]
 }
}

i also tried but gave me string and list wrong

with open('file.json', 'w') as file: file.write('{n' +',n'.join(json.dumps(f"{i}: {dd[i]}") for i in dd) +'n}')
# result
{
"A: {'a': {'1': 'b', '2': 'f'}, 'z': ['z', 'q']}",
"B: {'b': {'1': 'c', '2': 'g'}, 'z': ['x', 'p']}",
"C: {'c': {'1': 'd', '2': 'h'}, 'z': ['y', 'o']}"
}

the result i wanna is

    {
    "A": {"a": {"1": "b", "2": "f"}, "z": ["z", "q"]},
    "B": {"b": {"1": "c", "2": "g"}, "z": ["x", "p"]},
    "C": {"c": {"1": "d", "2": "h"}, "z": ["y", "o"]},
     }

how do i print the json content one line per dict while all inside is one line too?

i plan to read it using json.load

Asked By: yvgwxgtyowvaiqndwo

||

Answers:

Stdlib json module does not really support that, but you should be able to write a function which does similar pretty easily. Something like:

import json

def my_dumps(dd):
    lines = []
    for k, v in dd.items():
        lines.append(json.dumps({k: v})[1:-1])
    return "{n" + ",n".join(lines) + "n}"

If all you wanted was to wrap json to some more human-friendly line width, without totally spacing out everything like using indent option does, then another option might be using textwrap:

>>> print("n".join(textwrap.wrap(json.dumps(dd), 51)))
{"A": {"a": {"1": "b", "2": "f"}, "z": ["z", "q"]},
"B": {"b": {"1": "c", "2": "g"}, "z": ["x", "p"]},
"C": {"c": {"1": "d", "2": "h"}, "z": ["y", "o"]}}
Answered By: wim
x = ['{n']
for i in dd :
    x.append('"'+i+'": '+str(dd[i]).replace("'",'"')+",n")       
x[-1] = x[-1][:-2]
x.append("n}")
with open('file.json', 'w') as file: 
    file.writelines(x)

Image of the output :-

enter image description here

Answered By: Nehal Birla
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.