AlphaCodingSkills

Python - JSON


Advertisements

Previous Page Next Page

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.

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. 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)

Output

{'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)

Output

{'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 ObjectsJSON equivalent
dictObject
listArray
tupleArray
strString
intNumber
floatNumber
Truetrue
Falsefalse
Nonenull

Writing JSON to a file

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.

Output

{'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))

Output

{"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"
}

Previous Page Next Page