JSON is a syntax for storing data.
JSON is text written with the notation of JavaScript.
Python uses a package named json, it is called to manipulate JSON.
import json
You can use the method json.loads() to read JSON content in Python.
The result is stored in a Python dictionary.
import json
x = '{ "name": "patrik", "age":25, "city":"Paris"}'
# parser x:
y = json.loads(x)
print(y["city"])
You can convert a Python object using the method json.dumps().
import json
# object
x = {"name": "patrik", "age": 25, "city": "Paris"}
# convert to JSON:
y = json.dumps(x)
# the result is going to be a JSON
print(y)
Python objects can be converted to different types of JSON:
import json
x = {
"name": "Adam",
"age": 32.
"single": False,
"children": ("Leo","Arthur"),
"car": [
{"model": "Renault", "year": 2022},
]
}
print(json.dumps(x, indent=4))
Result:
{
"name": "Adam",
"age": 32,
"single": false,
"children": [
"L\u00e9o",
"Arthur"
],
"car": [
{
"model": "Renault",
"year": 2022
}
]
}
json.dumps(x, indent=4, sort_keys=True)
Please disable your ad blocker and refresh the window to use this website.