15

I am writing up something that will eventually output a json file.

This is what I have for testing at the moment

import json

my_list = [1, 2, 3]
my_dict = {"key": "value", "boolean": True}
my_json = {"object": my_dict, "array": my_list}

print(json.dumps(my_json, indent=4))

This will output:

{
    "object": {
        "key": "value",
        "boolean": true
    },
    "array": [
        1,
        2,
        3
    ]
}

What I don't want is a newline after each value in an array, purely for aesthetic purposes i.e.

"array": [1, 2, 3]

How would I go about doing this?

Geenium
  • 151
  • 1
  • 4
  • 3
    Have you tried removing the `indent=4` ? – Jon Clements Apr 30 '17 at 15:50
  • I guess you could use regex to search & replace. But how do you want to handle more complex JSON that contains lists & dicts nested inside other lists & dicts? To get complete control you can implement your own class that inherits from [`json.JSONEncoder`](https://docs.python.org/3/library/json.html#json.JSONEncoder). – PM 2Ring Apr 30 '17 at 15:56
  • 2
    Closed, but the link in the close message points to a much too complicated answer. Use this: `print(json.dumps(my_json, indent=None, separators=(",",":")))`, which results in compact one-line form `{"object":{"key":"value","boolean":true},"array":[1,2,3]}` – mgaert Apr 03 '20 at 08:33
  • An overeager close in me opinion. It's a very simple question and the close hint points to a very complex answer. mgaert above provided a one-liner that does the trick. – Dariusz Jul 31 '20 at 10:51
  • what about when the array is 100's or 1000's of items in length? how are you rendering the json string? maybe you can use a different program to render and explore the json like firefox or chrome browers which allow you to expand and collapse the shelves? – skullgoblet1089 Jul 31 '20 at 12:00

1 Answers1

5

Your task can be fulfilled by using a library like jsbeautifier

Install the library by using:

pip install jsbeautifier

Then add the options and call the jsbeautifier.beautify() function.

Full Code:

import json
import jsbeautifier


my_list = [1, 2, 3]
my_dict = {"key": "value", "boolean": True}
my_json = {"object": my_dict, "array": my_list}

options = jsbeautifier.default_options()
options.indent_size = 2
print(jsbeautifier.beautify(json.dumps(my_json), options))

Output:

{
  "object": {
    "key": "value",
    "boolean": true
  },
  "array": [1, 2, 3]
}
Harshana Serasinghe
  • 4,340
  • 1
  • 11
  • 21