While exchanging the data between browser and server, the data can only be text. JSON is widely used for storing and exchanging data between server and client in an AJAX application. JSON is a text which encodes Python objects as JSON, sends JSON to the server and decodes back into Python objects.
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. Please see the below example 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)
{'name': 'Marry', 'age': 25, 'city': 'London'}
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)
{'name': 'Marry', 'age': 25, 'city': 'London'}
The below table 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 |
TThe dumps() method of json module is used to write the JSON to a file. In the below example, 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)
The test.text file will contain the following data.
{'name': 'Marry', 'age': 25, 'city': 'London'}
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.
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))
{"city": "London", "name": "Marry", "age": 25} Applying indent: { "name": "Marry", "age": 25 "city": "London", } Applying indent and sort_keys: { "age": 25, "city": "London", "name": "Marry" }