Encoding JSON with Python

Python comes pre-equipped with a JSON encoder and decoder to make it very simple to play nice with JSON in your applications

The simplest way to encode JSON is with a dictionary. This basic dictionary holds random values of various datatypes.

data = {
    a: 0,
    b: 9.6,
    c: "Hello World",
    d: {
        a: 4
    }
}

We then use json.dumps() to convert the dictionary to a JSON object.

import json

data = {
    a: 0,
    b: 9.6,
    c: "Hello World",
    d: {
        a: 4
    }
}

json_data = json.dumps(data)
print(json_data)

This will print out

{"c": "Hello World", "b": 9.6, "d": {"e": [89, 90]}, "a": 0}

Notice how the keys are not sorted by default, you would have to add the sort_keys=True argument to json.dumps() like so.

import json

data = {
    a: 0,
    b: 9.6,
    c: "Hello World",
    d: {
        a: 4
    }
}

json_data = json.dumps(data, sort_keys=True)
print(json_data)

Which would then output the sorted keys.

{"a": 0, "b": 9.6, "c": "Hello World", "d": {"e": [89, 90]}}

Leave a Reply

Your email address will not be published. Required fields are marked *