Python - JSON
JavaScript Object Notation (JSON) is a language-independent data format for storing and exchanging data. It is a text-based format and it can easily be sent to and from a server, and used as a data format by any programming language. In case of Python language, JSON is a text which encodes Python objects as JSON, sends JSON to the server and decodes back into Python objects.
Parse JSON - Convert JSON to Python
To work with JSON data, Python has a built-in module called json which need to be imported in the current script. load() method of json module is used to convert JSON into Python object. See the example below for syntax.
import json # example JSON data json_data = '{ "name":"Marry", "age":25, "city":"London"}' # parse json_data MyDict = json.loads(json_data) # the result will be a Python dictionary: print(MyDict)
The output of the above code will be:
{'name': 'Marry', 'age': 25, 'city': 'London'}
Convert Python to JSON
To convert a Python object into JSON, dumps() method of json module is used.
import json #Create a Python dictionary MyDict = { "name":"Marry", "age":25, "city":"London" } #convert Python dictionary into JSON json_data = json.dumps(MyDict) #the result will be a Python dictionary: print(json_data)
The output of the above code will be:
{'name': 'Marry', 'age': 25, 'city': 'London'}
The table below shows the list of Python objects which can be converted into JSON and equivalent version of JSON.
Python Objects | JSON equivalent |
---|---|
dict | Object |
list | Array |
tuple | Array |
str | String |
int | Number |
float | Number |
True | true |
False | false |
None | null |
Writing JSON to a file
TThe dumps() method of json module is used to write the JSON to a file. In the example below, the test.text is opened in writing mode. If the file doesn't already exist, it will be created. Then, json.dump() is used to convert Python object into JSON and save it to the test.txt file.
import json #Create a Python dictionary MyDict = { "name":"Marry", "age":25, "city":"London" } with open('test.txt', 'w') as json_file: json.dump(MyDict, json_file) MyFile = open("test.txt", "r") #read content of the file print(MyFile.readlines())
The test.text file will contain the following data.
['{"name": "Marry", "age": 25, "city": "London"}']
Format the Result
To analyze and debug JSON data, it need to be printed in a more readable format. This can be done by passing additional parameters like indent and sort_keys to the json.dumps() method.
- indent: specify indent value to print the result in more readable format. The default value is None.
- sort_keys: specify True if the result need to be sorted. The default value of sort_keys is False.
import json #Create a Python dictionary MyDict = { "name":"Marry", "age":25, "city":"London" } print(json.dumps(MyDict)) print("\nApplying indent:") print(json.dumps(MyDict, indent=2)) print("\nApplying indent and sort_keys:") print(json.dumps(MyDict, indent=5, sort_keys=True))
The output of the above code will be:
{"name": "Marry", "age": 25, "city": "London"} Applying indent: { "name": "Marry", "age": 25, "city": "London" } Applying indent and sort_keys: { "age": 25, "city": "London", "name": "Marry" }