python logo

python json


Python hosting: Host, run, and code Python in the cloud!

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read and write. It is commonly used for asynchronous browser/server communication. This format facilitates smooth data transfer between a server and a web application. For instance, consider this sample JSON data:

1
2
3
4
5
6
7
8
9
10
11
12
{
"persons": [
{
"city": "Seattle",
"name": "Brian"
},
{
"city": "Amsterdam",
"name": "David"
}
]
}

The Python’s json module provides simple ways to encode and decode data in JSON format.

Related course:
Data Analysis with Python Pandas

JSON conversion examples

Convert JSON to Python Object (Dictionary)
To transform JSON into a Python dictionary, you can use the following code:

1
2
3
4
5
6
import json

json_data = '{"name": "Brian", "city": "Seattle"}'
python_obj = json.loads(json_data)
print(python_obj["name"])
print(python_obj["city"])

Convert JSON to Python Object (List)
JSON arrays can seamlessly be mapped to Python lists:

1
2
3
4
5
6
7
import json

array = '{"drinks": ["coffee", "tea", "water"]}'
data = json.loads(array)

for element in data['drinks']:
print(element)

Convert JSON to Python Object (float)
For floating point numbers, you can use the decimal library for precision:

1
2
3
4
5
6
import json
from decimal import Decimal

jsondata = '{"number": 1.573937639}'
x = json.loads(jsondata, parse_float=Decimal)
print(x['number'])

Complex JSON to Python Object Conversion (Example)
Handling complex JSON data that contains multiple objects:

1
2
3
4
5
6
7
8
9
import json

json_input = '{"persons": [{"name": "Brian", "city": "Seattle"}, {"name": "David", "city": "Amsterdam"} ] }'
try:
decoded = json.loads(json_input)
for x in decoded['persons']:
print(x['name'])
except (ValueError, KeyError, TypeError):
print("Error in JSON format")

Convert Python Object (Dictionary) to JSON
If you need to encode a Python object into JSON format, make use of the json.dumps() method:

1
2
3
4
5
6
7
import json

d = {}
d["Name"] = "Luke"
d["Country"] = "Canada"
print(json.dumps(d, ensure_ascii=False))
# result: {"Country": "Canada", "Name": "Luke"}

Mapping JSON data to Python objects
JSON data can be deserialized to Python objects using the json.loads() method. Here’s a quick reference table showcasing the mapping between JSON and Python data structures:

JSON Python
object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None

Pretty printing JSON in Python

To neatly display JSON data with proper indentation, you can utilize the json.dumps() function:

1
2
3
4
5
import json

json_data = '{"name": "Brian", "city": "Seattle"}'
python_obj = json.loads(json_data)
print(json.dumps(python_obj, sort_keys=True, indent=4))

Further Reading
For more insights on working with JSON data in Python, check out this tutorial on visualizing data using Google Charts with JSON.






Leave a Reply:




Jeremy Lee Sat, 23 May 2015

Warning: do not name your test file json.py (it's tempting for some reason). In general, don't name your source the same as pre-defined imported modules. The import looks in the local directory first.

Frank Sat, 23 May 2015

Correct, you cannot name your file json.py because we import json. This is the general case in python and can be confusing. Thanks for your comment