Python and JSON

JSON is a syntax for storing data.

JSON is text written with the notation of JavaScript.

Import JSON into Python

Python uses a package named json, it is called to manipulate JSON.

import json

Convert JSON to Python (Parse 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"])

Convert Python object to JSON

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:

  • dict -> Object
  • tuple -> Array
  • string -> String
  • list -> Array
  • int -> Number
  • float -> Number
  • True -> true
  • False -> false
  • None -> null

Beautify JSON)

To beautify the JSON format, the json.dumps() has parameters to make it easy to read the result:

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
}
]
}

Sort result

You can also sort the result by keys with the parameter sort_keys:

json.dumps(x, indent=4, sort_keys=True)