Reading and Writing JSON data in Python

Source:www.opentechguides.com | Date Published: 2019-05-02 15:50:11

JSON (Java Script Object Notation) is a data format for storing and exchanging structured data between applications. There is a standard library in Python called json for encoding and decoding JSON data. This article demonstrates how to read data from a JSON string/file and similarly how to write data in JSON format using json module in Python.

Say for example you have a string or a text file with the below JSON:

{  
   "name":"Jack",
   "age":30,
   "address":{  
      "street":"Station Road",
      "city":"London"
   },
   "phone":[  
      790156789,
      770198765
   ]
}

Note that the value of address field is another another JSON and the phone number field is an array that contains two numbers. Let's now learn how to read and print specific data items from this JSON data in your Python program.

Reading a JSON string

First you need to import the json module.

import json

Then assign the JSON string to a variable.

json_str = '{ "name":"Jack", "age":30, "address":{"street":"Station Road", "city":"London"}, "phone":[790156789, 770198765]}'

The json.loads function decodes a JSON string object to a Python dictionary.

contact = json.loads(json_str)

The variable contact is a dictionary that contains the JSON data.

json.loads() function performs the following conversions when decoding JSON data.

JSONPython
objectdict
arraylist
stringunicode
number(int)int, long
number (real)float
trueTrue
falseFalse
nullNone

The elements of the dictionary can be accessed using the get() method or by specifying the item key inside square brackets. Here are a few examples:

# using get method to access the elements
print(contact.get("address"))
print(contact.get("address").get("city"))

#using square brackets
print(contact["address"]["city"])
print(contact["phone"])       
print(len(contact["phone"]))  #No of elements in the list
print(contact["phone"][0])	  # First phone no in the array

# or a combination of both
print(contact["address"].get("city"))

Reading JSON from a file

In example explained above, the JSON data is stored in a string. If the JSON data is in a file instead of string, then replace json.loads() function with json.load() as shown in the next example.

with open('some-json-file.json', 'r') as f:
    json_dict = json.load(f)

The difference is, the argument to json.loads (pronounced load-s) function is a string and json.load function is a file pointer.

Writing a Python dict object as JSON string

You can convert a Python dictionary object to a JSON string using the json.dumps() function. The below code serialises the Python dictionary object person_dict to a JSON string.

contact_dict = {"name":"Jill", 
	"age":32, 
	"address":{"street" : "London Road", 
				"city":"Bristol"
				} 
	}
contact_json = json.dumps(person_dict)
print(contact_json)

The following arguments can be passed to json.dumps function to format the output to look even better.

Writing JSON to a file

To output the JSON to a file, open the file, say contacts.json for example, in write mode and use the json.dump() function to convert the dictionary person_dict to a string and save to the file contacts.json. If the file does not already exist then it will be created.

with open('contacts.json', 'w') as json_file:
  json.dump(person_dict, json_file)

Open Tech Guides | www.opentechguides.com