Convert a dictionary to a json string in Python

You can convert a dictionary to a JSON string by json.dumps() in json module.

import json

s = {'a': 1, 'b': 2}
j = json.dumps(s)

print(j)  # {"a": 1, "b": 2}
print(type(j))  # <class 'str'>

s is a dicttionary and j is a string formatted in JSON. Writing a dict in a json file needs that conversion.

import json

s = {'a': 1, 'b': 2}
j = json.dumps(s)

with open('a.json', 'w') as f:
    f.write(j)

a.json

{"a": 1, "b": 2}

Indent

You can set the indent parameter in json.dumps().

import json

d = {
    'Bob': {'age': 37, 'role': 'admin'},
    'John': {'age': 25},
}

j1 = json.dumps(d, indent=2)
j2 = json.dumps(d, indent=4)

print(j1)
# {
#   "Bob": {
#     "age": 37,
#     "role": "admin"
#   },
#   "John": {
#     "age": 25
#   }
# }

print(j2)
# {
#     "Bob": {
#         "age": 37,
#         "role": "admin"
#     },
#     "John": {
#         "age": 25
#     }
# }

The first JSON-formatted string has 2 indents and the second has 4 indents. The default indent is None meaning no indentation.

import json

d = {
    'Bob': {'age': 37, 'role': 'admin'},
    'John': {'age': 25},
}

j = json.dumps(d)

print(j)
# {"Bob": {"age": 37, "role": "admin"}, "John": {"age": 25}}

Sort by keys

With setting sort_keys parameter (boolean), you can sort the output string by ascending or descending.

import json

d = {
    'Bob': {'skill': 'C++', 'age': 37},
    'Alicia': {'skill': 'Java', 'age': 29},
    'John': {'skill': 'Python', 'age': 25},
}

j1 = json.dumps(d, indent=2)
j2 = json.dumps(d, indent=2, sort_keys=True)
j3 = json.dumps(d, indent=2, sort_keys=False)

print(j1)
# {
#   "Bob": {
#     "skill": "C++",
#     "age": 37
#   },
#   "Alicia": {
#     "skill": "Java",
#     "age": 29
#   },
#   "John": {
#     "skill": "Python",
#     "age": 25
#   }
# }

print(j2)
# {
#   "Alicia": {
#     "age": 29,
#     "skill": "Java"
#   },
#   "Bob": {
#     "age": 37,
#     "skill": "C++"
#   },
#   "John": {
#     "age": 25,
#     "skill": "Python"
#   }
# }

print(j3)
# {
#   "Bob": {
#     "skill": "C++",
#     "age": 37
#   },
#   "Alicia": {
#     "skill": "Java",
#     "age": 29
#   },
#   "John": {
#     "skill": "Python",
#     "age": 25
#   }
# }

When sort_keys is true, all keys over all hierarchy are sorted by alphabetically ascending so Bob is after Alicia and skill is after age in the second output. If you don't set this parameter, the order is the same as the order of the original dictionary.

Comments

Powered by Markdown

More