Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, json dump a list with no newlines

Tags:

python

json

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?

like image 939
Geenium Avatar asked Apr 30 '17 15:04

Geenium


1 Answers

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]
}
like image 107
Harshana Serasinghe Avatar answered Nov 09 '22 17:11

Harshana Serasinghe