21

I have this code:

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))

I get an output like:

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

I want it the elements of the "array" array to appear on the same line, like so:

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

How can I get this result?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Geenium
  • 311
  • 1
  • 2
  • 4
  • 5
    Have you tried removing the `indent=4` ? – Jon Clements Apr 30 '17 at 15:50
  • 1
    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
  • 4
    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

2 Answers2

9

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
  • 5,151
  • 1
  • 17
  • 27
1

You don't need any new module to solve this problem. The JSON output is a string type and you can use a loop and an if/elif/else to solve it as in the example below:

import json

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

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

str_to_write = ''
skip = 0
for char in json_dumps :
    if (skip == 1) and ((char == '\n') or (char == ' ')) :
        pass
    elif (char == '[') :
        skip = 1
        str_to_write = str_to_write + char
    elif (char == ']') :
        skip = 0
        str_to_write = str_to_write + char
    else :
        str_to_write = str_to_write + char

print(str_to_write)

Unfortunatly, it also strips the space character inside the lists. The output is:

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

Using regex module, you can keep the spaces:

import regex as re
import json

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

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

start = [m.start() for m in re.finditer('\[', json_dumps)]
end = [m.start() + 1 for m in re.finditer('\]', json_dumps)]
original = []
alterated = []
for s, e in zip(start, end) :
    original.append(json_dumps[s:e])
    alterated.append(json_dumps[s:e].replace('\n', '').replace('    ', '').replace(',', ', '))
for o, a in zip(original, alterated) :
    json_dumps = json_dumps.replace(o, a)

print(json_dumps)

The output:

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