Json in Python

Python provides built-in support for JSON encoding and decoding, including to and from built-in and custom data types.

import json

# We'll use these two classes to demonstrate encoding and
# decoding of custom types below.
class Response1:
    def __init__(self, page, fruits):
        self.page = page
        self.fruits = fruits

class Response2:
    def __init__(self, page, fruits):
        self.page = page
        self.fruits = fruits

def main():
    # First we'll look at encoding basic data types to
    # JSON strings. Here are some examples for atomic
    # values.
    print(json.dumps(True))
    print(json.dumps(1))
    print(json.dumps(2.34))
    print(json.dumps("gopher"))

    # And here are some for slices and maps, which encode
    # to JSON arrays and objects as you'd expect.
    print(json.dumps(["apple", "peach", "pear"]))
    print(json.dumps({"apple": 5, "lettuce": 7}))

    # The json package can automatically encode your
    # custom data types. It will only include public
    # attributes in the encoded output and will by default
    # use those names as the JSON keys.
    res1 = Response1(page=1, fruits=["apple", "peach", "pear"])
    print(json.dumps(res1.__dict__))

    # You can use a custom encoder to customize the encoding process.
    def custom_encoder(obj):
        if isinstance(obj, Response2):
            return {"page": obj.page, "fruits": obj.fruits}
        return obj.__dict__

    res2 = Response2(page=1, fruits=["apple", "peach", "pear"])
    print(json.dumps(res2, default=custom_encoder))

    # Now let's look at decoding JSON data into Python
    # values. Here's an example for a generic data
    # structure.
    byt = b'{"num":6.13,"strs":["a","b"]}'

    # We need to provide a variable where the JSON
    # package can put the decoded data. This
    # dict will hold a dictionary of strings
    # to arbitrary data types.
    dat = json.loads(byt)
    print(dat)

    # In order to use the values in the decoded map,
    # we can directly access them with the appropriate type.
    num = dat["num"]
    print(num)

    # Accessing nested data is straightforward.
    strs = dat["strs"]
    str1 = strs[0]
    print(str1)

    # We can also decode JSON into custom data types.
    # This has the advantages of adding additional
    # type-safety to our programs and eliminating the
    # need for type assertions when accessing the decoded
    # data.
    str_data = '{"page": 1, "fruits": ["apple", "peach"]}'
    res = json.loads(str_data)
    print(res)
    print(res["fruits"][0])

    # In the examples above we always used strings as intermediates between the data and
    # JSON representation. We can also stream JSON encodings directly to file-like objects.
    import sys
    json.dump({"apple": 5, "lettuce": 7}, sys.stdout)
    print()  # Add a newline for better formatting

if __name__ == "__main__":
    main()

To run the program, save it as json_example.py and use python:

$ python json_example.py
true
1
2.34
"gopher"
["apple", "peach", "pear"]
{"apple": 5, "lettuce": 7}
{"page": 1, "fruits": ["apple", "peach", "pear"]}
{"page": 1, "fruits": ["apple", "peach", "pear"]}
{'num': 6.13, 'strs': ['a', 'b']}
6.13
a
{'page': 1, 'fruits': ['apple', 'peach']}
apple
{"apple": 5, "lettuce": 7}

We’ve covered the basics of JSON in Python here, but check out the Python JSON documentation for more details.

Python’s json module provides a simple and efficient way to work with JSON data. It can handle encoding and decoding of Python objects to and from JSON, making it easy to work with web APIs and data interchange formats.