You can parse a JSON string in Python using the json.loads()
method, which deserializes the JSON string to a Python object. You can use it like so:
import json
data = json.loads('{"name": "John Doe", "age": 29}')
print(data['name']) # "John Doe"
print(data['age']) # 29
To see the types of the decoded objects, you can get the class name of the objects like so:
print(type(data['name']).__name__) # str
print(type(data['age']).__name__) # int
The json.loads()
method is able to make the following JSON transformations:
JSON | Python |
---|---|
object |
dict |
array |
list |
string |
str |
number (int) |
int |
number (real) |
float |
true |
True |
false |
False |
null |
None |
For example:
import json
data = json.loads('{"foo":"bar"}')
# object -> dict
print(data) # {'foo': 'bar'}
print(type(data).__name__) # dict
import json
data = json.loads('["foo", "bar"]')
# array -> list
print(data) # ['foo', 'bar']
print(type(data).__name__) # list
import json
data = json.loads('{"foo": "bar"}')
# string -> str
print(data['foo']) # 'bar'
print(type(data['foo']).__name__) # str
import json
data = json.loads('{"foo": 2, "bar": 1.5}')
# number (int) -> int
print(data['foo']) # 2
print(type(data['foo']).__name__) # int
# number (real) -> float
print(data['bar']) # 1.5
print(type(data['bar']).__name__) # float
import json
data = json.loads('{"foo": true, "bar": false}')
# true -> True
print(data['foo']) # True
print(type(data['foo']).__name__) # bool
# false -> False
print(data['bar']) # False
print(type(data['bar']).__name__) # bool
import json
data = json.loads('{"foo": null}')
# null -> None
print(data['foo']) # None
print(type(data['foo']).__name__) # NoneType
In addition to these, Python is also able to decode NaN
, Infinity
and -Infinity
(even though they're not valid JSON):
JSON | Python |
---|---|
NaN |
nan |
Infinity |
inf |
-Infinity |
-inf |
For example:
import json
data = json.loads('{"foo": NaN, "bar": Infinity, "baz": -Infinity}')
# NaN -> nan
print(data['foo']) # nan
print(type(data['foo']).__name__) # float
# Infinity -> inf
print(data['bar']) # inf
print(type(data['bar']).__name__) # float
# -Infinity -> -inf
print(data['baz']) # -inf
print(type(data['baz']).__name__) # float
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.