JSON

What is JSON? The Java Script Object Notation has become a widely accepted and commonly used means of storing or sharing structured data. If you start using network sockets, build websites or retrieve data from web API’s you are probably going to need to deal with it.

JSON uses a slightly different naming scheme for it’s variable types. The Python library will convert using the following table:

JSON object array string number (int) number (float) true false null
Python dict list str int float True False None

Serialising & Deserialising JSON

Serialising and deserialising are just fancy names for converting the data to a string, and then back again.

Here are some functions that are useful for getting started with JSON:

Read/write JSON files

Add the following to your files.py file to provide JSON file functionality.

import json

def read_json( filename ):
    with open(filename, "r", encoding="utf-8") as f:
        content = json.load(f)
    return content

def write_json( filename, data ):
    with open(filename, "w", encoding="utf-8") as f:
        json.dump(data, f)

Example usage:

import files

countries = read_json("countries.json")
for val in countries:
    country = val["name"]
    code = val["code"]
    continent = val["continent"]
    print("The country {} has code {} and is in the continent of {}.".format(country, code, continent))