1. What is JSON?
JSON is a data format that uses plain text, JSON format uses key-value pairs for the data to use. JSON was originally developed for use in JavaScript applications. The JSON term itself stands for JavaScript Object Notation. However, since JSON is a data format, it can be used by any language without limitation with JavaScript.
2. JSON in Python
Python has a built-in caller called json
that can be used to work with JSON data.
1 2 | import json |
1. Convert JSON in Python
Use the json.loads()
function to convert a JSON string to Dictionary
1 2 3 4 5 6 7 8 9 10 11 | import json # some JSON: x = '{ "name":"John", "age":30, "city":"New York"}' # parse x: y = json.loads(x) # the result is a Python dictionary: print(y["age"]) |
2. Convert the Python object to JSON
Use the json.dumps()
function to convert a Python Object into a JSON string
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import json # a Python object (dict): x = { "name": "John", "age": 30, "city": "New York" } # convert into JSON: y = json.dumps(x) # the result is a JSON string: print(y) |
The list of objects can be converted to a JSON string
- dict
- list
- tuple
- string
- int
- float
- True
- False
- None
1 2 3 4 5 6 7 8 9 10 11 12 | import json print(json.dumps({"name": "John", "age": 30})) print(json.dumps(["apple", "bananas"])) print(json.dumps(("apple", "bananas"))) print(json.dumps("hello")) print(json.dumps(42)) print(json.dumps(31.76)) print(json.dumps(True)) print(json.dumps(False)) print(json.dumps(None)) |
Object conversion table between Python and JSON
Python | JSON |
---|---|
dict | Object |
list | Array |
tuple | Array |
str | String |
int | Number |
float | Number |
True | true |
False | false |
None | null |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import json x = { "name": "John", "age": 30, "married": True, "divorced": False, "children": ("Ann","Billy"), "pets": None, "cars": [ {"model": "BMW 230", "mpg": 27.5}, {"model": "Ford Edge", "mpg": 24.1} ] } print(json.dumps(x)) |
3. Format display
For a nice display, it is easier to see json.dumps()
provides an additional indent
parameter to format the indent number (1 indent equals 1 space)
1 2 | json.dumps(x, indent=4) |
4. Arrange the key
By default JSON will display the keys out of order. To sort keys, json.dumps()
provides the sort_keys
parameter
1 2 | json.dumps(x, indent=4, sort_keys=True) |
3. Conclusion
The json
module in Python also integrates many other features in the above methods. The next part I will provide more for you. Source: https://www.w3schools.com/python/python_json.asp