JSON
JSON, or JavaScript Object Notation, is a syntax for serializing different data types in human-readable text form. Within Python it is implemented as the json
module and the data model is similar as a dictionary.
Convert from JSON to Python
Python has a built-in JSON parser called the json
module. This module can be used to convert JSON data to Python objects. In the example below a JSON string is converted to a Python dictionary with json.loads()
and can be accessed as a Python dictionary.
1#!/usr/bin/env python3
2
3import json
4
5def main():
6 x = '{"name":"jack","age":42,"city":"Chicago"}'
7 y = json.loads(x)
8 print(y["age"])
9
10
11if __name__ == "__main__":
12 main()
142
Convert from Python to JSON
The Python module json
can be used to convert Python objects to JSON data. In the example below a Python dictionary is converted to a JSON string with json.dumps()
.
1#!/usr/bin/env python3
2
3import json
4
5def main():
6 x = {
7 "name": "Jack",
8 "age": 42,
9 "city": "Chicago"
10 }
11 y = json.dumps(x)
12 print(y)
13
14
15if __name__ == "__main__":
16 main()
1"{ \"name\":\"jack\", \"age\":42, \"city\":\"Chicago\"}"
When you convert from Python to JSON, Python objects are converted into the JSON (JavaScript) equivalent:
Python |
JSON |
---|---|
dict |
Object |
list |
Array |
tuple |
Array |
str |
String |
int |
Number |
float |
Number |
True |
true |
False |
false |
None |
null |
1#!/usr/bin/env python3
2
3import json
4
5def main():
6 print(json.dumps({"name": "Jack", "age": 42}))
7 print(json.dumps(["apple", "bananas"]))
8 print(json.dumps(("apple", "bananas")))
9 print(json.dumps("hello"))
10 print(json.dumps(42))
11 print(json.dumps(31.76))
12 print(json.dumps(True))
13 print(json.dumps(False))
14 print(json.dumps(None))
15
16
17if __name__ == "__main__":
18 main()
1"{"name":"Jack","age":42}"
2"[\"apple\",\"bananas\"]"
3"[\"apple\",\"bananas\"]"
4"\"hello\""
5"42"
6"31.76"
7"true"
8"false"
9"null"
Format the Result
Use the indent parameter to define the numbers of indents:
1json.dumps(x, indent=4)
Use the separators parameter to change the default separator:
1json.dumps(x, indent=4, separators=(". ", " = "))
Use the sort_keys parameter to specify if the result should be sorted or not:
1json.dumps(x, indent=4, sort_keys=True)