JSON (JavaScript Object Notation) is a syntax for storing and exchanging data. JSON is text, written with JavaScript object notation.
Python has a built-in package called json, which can be used to work with JSON data.
If you have a JSON string, you can parse it by using the json.loads() method. The result will be a Python dictionary.
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"])
If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.
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 json.dumps() method has parameters to make it easier to read the result:
# Use the indent parameter to define the numbers of indents: json.dumps(x, indent=4)Use the separators parameter to change the default separator:
json.dumps(x, indent=4, separators=(". ", " = "))