Python3 JSON Data Parsing
JSON (JavaScript Object Notation) is a lightweight data interchange format.
If you are not familiar with JSON, you can read our JSON Tutorial first.
In Python3, you can use the json module to encode and decode JSON data. It includes two functions:
- json.dumps(): Encodes data.
- json.loads(): Decodes data.
During the encoding and decoding process of JSON, Python's native types are converted to JSON types and vice versa. The specific conversion mappings are as follows:
Python to JSON Type Conversion Table:
Python | JSON |
---|---|
dict | object |
list, tuple | array |
str | string |
int, float, int- & float-derived Enums | number |
True | true |
False | false |
None | null |
JSON to Python Type Conversion Table:
JSON | Python |
---|---|
object | dict |
array | list |
string | str |
number (int) | int |
number (real) | float |
true | True |
false | False |
null | None |
json.dumps and json.loads Examples
The following example demonstrates converting Python data structures to JSON:
Example (Python 3.0+)
#!/usr/bin/python3
import json
# Convert Python dictionary type to JSON object
data = {
'no': 1,
'name': 'tutorialpro',
'url': 'http://www.tutorialpro.org'
}
json_str = json.dumps(data)
print("Python original data:", repr(data))
print("JSON object:", json_str)
Executing the above code outputs:
Python original data: {'url': 'http://www.tutorialpro.org', 'no': 1, 'name': 'tutorialpro'}
JSON object: {"url": "http://www.tutorialpro.org", "no": 1, "name": "tutorialpro"}
From the output, it can be seen that simple types, after encoding, are very similar to their original repr()
output.
Continuing from the previous example, we can convert a JSON encoded string back to a Python data structure:
Example (Python 3.0+)
#!/usr/bin/python3
import json
# Convert Python dictionary type to JSON object
data1 = {
'no': 1,
'name': 'tutorialpro',
'url': 'http://www.tutorialpro.org'
}
json_str = json.dumps(data1)
print("Python original data:", repr(data1))
print("JSON object:", json_str)
# Convert JSON object back to Python dictionary
data2 = json.loads(json_str)
print("data2['name']: ", data2['name'])
print("data2['url']: ", data2['url'])
Executing the above code outputs:
Python original data: {'name': 'tutorialpro', 'no': 1, 'url': 'http://www.tutorialpro.org'}
JSON object: {"name": "tutorialpro", "no": 1, "url": "http://www.tutorialpro.org"}
data2['name']: tutorialpro
data2['url']: http://www.tutorialpro.org
If you are dealing with files instead of strings, you can use json.dump() and json.load() to encode and decode JSON data. For example:
Example (Python 3.0+)
#!/usr/bin/python3
import json
# Example code for json.dump() and json.load()
# (not provided in the original text)
# Write JSON data
with open('data.json', 'w') as f:
json.dump(data, f)
# Read data
with open('data.json', 'r') as f:
data = json.load(f)
For more information, please refer to: https://docs.python.org/3/library/json.html