JSON in Python

What is JSON

Definition

JSON is Javascript Object Notation. JSON is a light weight data exchange format. JSON string is a string that satisfies JSON format.

{"name": "Isaac Zhou"}

{'name': 'Isaac Zhou'}

The above is a typical JSON string. JSON has several benefits:

  1. easy to read
  2. easy to analyze
  3. efficient with the network transaction
  4. It can transfer data across different languages

Deserialize JSON in Python

The original format of JSON is a string, we need to deserialize it in Python.

json_str = "{name: isaac, age: 33}"

We can use json module in Python, however we need to be careful with json str in python:

  1. all the keys should be str
  2. all non-number should be str
  3. only "" is accepted
  4. note that json’s bool is true or false, whereas in Python it’s True or False
  5. null is JSON whereas it’s None in Python

    import json

    json_str = ‘{“name”: “Isaac Zhou”, “age”:33, “flag”:true}’

    r = json.loads(json_str)

    r

    {‘name’: ‘Isaac Zhou’, ‘age’: 33, ‘flag’: True}

In Python, now we can use it like a dictionary. (Note in other languages, it might be converted to a different data structure)

type(r)

dict

r["age"]

33

JSON str converted to a list

import json

json_str = '[{"name": "Isaac Zhou", "age":33}]'

r = json.loads(json_str)

type(r)

list

r[0]["age"]

33

Serialize Python Data to JSON

Convert a native Python data to JSON

import json

my_dict = [
    {"name": "Isaac", "title": "Data Scientist", "level": "chief", "owner?":False},
    {"name": "Allen", "title": None, "level": "CEO", "owner?": True}
]

json_str = json.dumps(my_dict)

json_str

'[{"name": "Isaac", "title": "Data Scientist", "level": "chief", "owner?": false}, {"name": "Allen", "title": null, "level": "CEO", "owner?": true}]'

Now check the data type

type(json_str)

str