How to save a dictionary in a json file with python ?

Published: April 12, 2019

DMCA.com Protection Status

Examples of how to save a dictionary in a json (JavaScript Object Notation) file with python

See also: pickle — Python object serialization and marshal — Internal Python object serialization

Save a python dictionary in a json file

To save a dictionary in python to a json file, a solution is to use the json function dump(), example:

import json

dict = {"member #002":{"first name": "John", "last name": "Doe", "age": 34},
        "member #003":{"first name": "Elijah", "last name": "Baley", "age": 27},
        "member #001":{"first name": "Jane", "last name": "Doe", "age": 42}}

with open('data.json', 'w') as fp:
    json.dump(dict, fp)

the above script will then create the following json file called here 'data.json':

{"member #002": {"first name": "John", "last name": "Doe", "age": 34}, "member #003": {"first name": "Elijah", "last name": "Baley", "age": 27}, "member #001": {"first name": "Jane", "last name": "Doe", "age": 42}}

Prettify the json file

To prettify the json file and to .make it more readable, a solution is to use the option indent in the function dump(), example:

import json


dict = {"member #002":{"first name": "John", "last name": "Doe", "age": 34},
        "member #003":{"first name": "Elijah", "last name": "Baley", "age": 27},
        "member #001":{"first name": "Jane", "last name": "Doe", "age": 42}}


with open('data.json', 'w') as fp:
    json.dump(dict, fp,  indent=4)

returns

{
    "member #002": {
        "first name": "John",
        "last name": "Doe",
        "age": 34
    },
    "member #003": {
        "first name": "Elijah",
        "last name": "Baley",
        "age": 27
    },
    "member #001": {
        "first name": "Jane",
        "last name": "Doe",
        "age": 42
    }
}

Sort the json file

With the option sort_keys=True it is also possible to sort the json file:

import json


dict = {"member #002":{"first name": "John", "last name": "Doe", "age": 34},
        "member #003":{"first name": "Elijah", "last name": "Baley", "age": 27},
        "member #001":{"first name": "Jane", "last name": "Doe", "age": 42}}


with open('data.json', 'w') as fp:
    json.dump(dict, fp, sort_keys=True, indent=4)

returns

{
    "member #001": {
        "age": 42,
        "first name": "Jane",
        "last name": "Doe"
    },
    "member #002": {
        "age": 34,
        "first name": "John",
        "last name": "Doe"
    },
    "member #003": {
        "age": 27,
        "first name": "Elijah",
        "last name": "Baley"
    }
}

References