#23 JSON Module / Python Lessons for Beginners

by Alex
#23 JSON Module / Python Lessons for Beginners

Previous lesson: Dates in Python JSON is a syntax for storing and exchanging data. JSON is text written in the style of a JavaScript object.

JSON in Python

Python has a built-in json module that can be used to handle JSON data.

import json

Full documentation on the JSON module for Python 3 in Russian: JSON Python module for working with the .json format

Converting from JSON to Python

If you have a JSON string, you can parse over it using the json.loads () method. The result will be a python dictionary. Convert from JSON to Python:

import json
# some JSON:
x = '{"name": "Viktor", "age":30, "city": "Minsk"}'
# parsing x:
y = json.loads(x)
# the result will be a Python dictionary:
print(y["age"])

Output:

30

Convert from Python to JSON

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

import json
# create a dictionary x:
x = {
"name": "Viktor",
"age": 30,
"city": "Minsk"
}
# convert to JSON:
y = json.dumps(x)
# as a result we get JSON strings:
print(y)

Output:

{ "name": "Viktor", "age": 30, "city": "Minsk"}

You can convert the following Python object types to JSON strings:

  • dict
  • list
  • tuple
  • string
  • int
  • float
  • True
  • False
  • None

Convert Python objects to JSON strings and output values:

import json
print(json.dumps({"name": "Viktor", "age": 30})
print(json.dumps(["Porsche", "BMW"]))
print(json.dumps("Porsche", "BMW"))
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))

Output:

{ "name": "Viktor", "age": 30}
{ "Porsche", "BMW"]
{ "Porsche", "BMW"]
"hello."
42
31.76
true
false
null

When you convert from Python to JSON, Python objects are converted to the JSON equivalent: PythonJSONdictObjectlistArraytupleArraystrStringintNumberfloatNumberTruetrueFalsefalseNonenull Convert a Python object containing all convertible data types:

import json
x = {
{ "name": "Viktor",
{ "age": 30,
"married": True,
"divorced": False,
"children": ("Anna", "Bogdan"),
"pets": None,
"cars": [
{ "model": "BMW 230", "mpg": 27.5},
{ "model": "Ford Edge", "mpg": 24.1}
]
}
print(json.dumps(x))

Output:

{ "name": "Viktor", "age": 30, "married": true, "divorced": false, "children": ["Anna", "Bogdan"], "pets": null, "cars": [{"model": "BMW 230", "mpg": 27.5}, {"model": "Ford Edge", "mpg": 24.1}]}

How to convert Cyrillic

If the Python data contains Cyrillic characters, the json.dumps() method converts them to the default encoding. To preserve the Cyrillic characters, use the parameter ensure_ascii=False

import json
x = {
{ "name": "Victor"
}
y = {
{ "name": "Victor"
}
print(json.dumps(x))
print(json.dumps(y, ensure_ascii=False))

Output:

{"name": "\u0412\u0438\u043a\u0442\u043e\u0440"}
{ "name": "Victor"}

Formatting the result

The above example outputs a JSON string, but it’s not easy to read without indentation and line breaks. The method json.dumps() has parameters to make the result easier to read. We use the indent parameter to determine the number of indents:

json.dumps(x, indent=4)

You can also define delimiters whose default value is ,, :, where a comma and a space are used to separate each object, and a colon and a space are used to separate keys and values. Use the separators parameter to change the default separator:

json.dumps(x, indent=4, separators=(". ", " = "))

Arranging the result

The json.dumps() method has parameters to sort the keys in the result. Use the sort_keys parameter to specify whether the result should be sorted.

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

Related Posts

LEAVE A COMMENT