Sep. 14, 2015

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]}}

Recommended Python Training – DataCamp

For Python training, our top recommendation is DataCamp.

Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.

Datacamp has beginner to advanced Python training that programmers of all levels benefit from.

 



Read more about:
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, PythonForBeginners.com only recommend products or services that we try personally and believe will add value to our readers.