Python JSON

Python JSON Parsing

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.


Parse JSON - Convert from JSON to Python

If you have a JSON string, you can parse it by using the json.loads() method. The result will be a Python dictionary.

JSON to Python

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"])


Convert from Python to JSON

If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.

Python to JSON

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)


Formatting the Result

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=(". ", " = "))