Explain JSON format and how to working with JSON in Python.

What is JSON ?

JSON is data format for sharing data. It is readable lightweight and is good replace for XML. Following is JSON data example.


Some important notes on JSON from example are:

Import JSON package

To working with JSON, Python has json package. So, the first step is import the package

import json

json package provide the ability to transfer between JSON text and Python object (like dictionary)

Working with JSON string

For working with JSON string, json package provide 2 functions :

For example following code load pets in to parsed_json object

import json

# example of json string
pets = '''{
  "pets": [
      "name" : "Purrsloud",
      "species" : "Cat",
      "favFoods" : ["wet food", "dry food", "any food"],
      "birthYear" : 2016,
      "photo" : "https://learnwebcode.github.io/json-example/images/cat-2.jpg"
      "name" : "Barksalot",
      "species" : "Dog",
      "birthYear" : 2008,
      "photo" : "https://learnwebcode.github.io/json-example/images/dog-1.jpg"

# from JSON-string to Python-dictionary
parsed_json = json.loads(pets)

Now if you want to access the name of first pet :

# access the name of first pet

Let do some explain here, and understand how it work

Now if you want dump back from Python object to JSON string

# dump back from dictionary to json string
back_to_json_string = json.dumps(parsed_json)
print back_to_json_string

Working with JSON file

2 following function used to working with JSON file (which has extension is .json) :

Suppose we want to load data from sample.json file (this file has same JSON content)

parsed_json_from_file = json.load(open('sample.json'))

After that the way to access data from Python object is the same

# access the name of first pet

Now if you want to dump back from Python object to file

with open('sample_dump.json', 'w') as outfile:
	json.dump(parsed_json_from_file, outfile)

All my best course on python and data engineer