skip to Main Content

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

2

Answers


  1. 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"]}}
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search