0

I am exporting a dictionary containing values as list to a json file, but I am facing a indentation problem...

import json
null=None
json_data={
    'A': [null, null],
    'B': [null, null],
    'C': [null, null]
}
outfile=open('Export.json',"w")
json.dump(json_data, outfile, indent=2)
outfile.close()

What I get inside the json file:

{
  'A': [
    null,
    null
  ],
  'B': [
    null,
    null
  ]
  'C': [
    null,
    null
  ]
}

What I expected:

{
  'A': [null, null],
  'B': [null, null],
  'C': [null, null]
}

I used sort_keys=False but still getting the same output, what can I do?

Akascape
  • 219
  • 2
  • 11
  • 1
    In what way is that a "problem"? Note that your expected output is missing the `,` after each row. And why would you not expect `'A': [null, null], 'B': [null, null], 'C': [null, null]` in a single line if you expect the nulls to be in the same line!? – luk2302 Jul 14 '22 at 16:09
  • No, I forgot to add the `,` but how to solve? – Akascape Jul 14 '22 at 16:13
  • Still, the other two points / questions remain. – luk2302 Jul 14 '22 at 16:14
  • @luk2302 Because I used indent=2, if I remove that then I get the result in one line – Akascape Jul 14 '22 at 16:17
  • Well, there you have your answer / problem: you want both indentation (for the first level) and no indentation (for the second level) - that does not work, at least not with the `json` module. – luk2302 Jul 14 '22 at 16:19
  • Is there any other way to get the output I expected? – Akascape Jul 14 '22 at 16:20
  • What is the reason do you want your output to look like this? – Antony Hatchkins Jul 14 '22 at 16:25
  • You could search for JSON pretty printers, one may better satisfy your style needs. You could even write your own pretty printer in python. As far as JSON in a file or sent on the wire, computers don't care about the esthetics, they just want to parse the data. It would make sense to use an external tool that does fancy printing when needed and just dump the JSON compactly. – tdelaney Jul 14 '22 at 16:28

0 Answers0