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.
JSON | Python |
---|---|
object | dict |
array | list |
string | unicode |
number(int) | int, long |
number (real) | float |
true | True |
false | False |
null | None |
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.
- indent - No of spaces of indentation at each level of key-value pair. This comes very handy when you want to pretty print a very large JSON string. Default is None.
- sort_keys - A Boolean flag when set to True will sort the keys in the JSON string. Default is False
- skipkeys - A Boolean flag when set to true will skip any keys in the dict that are not of a basic Python data type instead of raising a TypeError. For example if there a key in the dict which is a tuple like ('A','B') and skipkeys is False then json.dump() will raise an error. If skipkeys is True then that key-value pair is skipped instead of raising an error.
- separators - A tuple that specifies the item separator and key separator. Default is (', ', ': ')/li>
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)