1

I am using python's json to produce a json file and cannot manage to format it the way I want.

What I have is a dictionary with some keys, and each key has a list of numbers attached to it:

out = {"a": [1,2,3], "b": [4,5,6]}

What I want to do is produce a JSON string where each list is in its own line, like so:

{
    "a": [1,2,3],
    "b": [4,5,6]
}

However, I can only get

>>> json.dumps(out)
'{"a": [1, 2, 3], "b": [4, 5, 6]}'

which has no new lines, or

>>> print json.dumps(out, indent=2)
{
  "a": [
    1, 
    2, 
    3
  ], 
  "b": [
    4, 
    5, 
    6
  ]
}

which has waaay to many. Is there a simply way to produce the string I want? I can do it manually, of course, but I am wondering if it is possible with json alone...

3
  • 1
    Nope, that was never the goal of the python json module. Why do you want to control the format so specifically? JSON parsers don't care. Commented Feb 15, 2016 at 10:23
  • @MartijnPieters Thanks for the quick answer. Do you know of any other module that can do what I want? Commented Feb 15, 2016 at 10:24
  • Nope, I'm not aware of any code that gives you this much control over the JSON output produced. Commented Feb 15, 2016 at 10:24

1 Answer 1

1

You can't do that with the json module, no. It was never the goal for the module to allow this much control over the output.

The indent option is only meant to aid debugging. JSON parsers don't care about how much whitespace is used in-between elements.

Sign up to request clarification or add additional context in comments.

1 Comment

I understand that, yes. However, since JSON is still a human-readable serialization, I thought maybe there is some way. Oh well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.