DEV Community

Cover image for Python JSON
Python64
Python64

Posted on

Python JSON

We will introduce how to use the Python language to encode and decode JSON objects. JSON (JavaScript Object Notation) is often used in the web, Python can handle it just as well.

Before using Python JSON encode or decode data, we need to first install module json. You can use the pip package manager to do that.

pip install json

After that you will be able to work with json data. Data in json format looks something like this:

{
"name":"Trevor",
"age":25,
"cars":[ "BMW", "Tesla", "Lamborghini" ]
}

JSON data is often returned from so called APIs, backends of web applications. If you are new to to Python, you may like this book

JSON Functions

Using JSON jsonlibrary functions (need to import: import json). You get these functions:

Function Description
json.dumps encoding object to a JSON string Python
json.loads to decode the encoded JSON string into Python objects

json.dumps

Python json.dumps for encoding objects into JSON string.
The following examples array JSON format data encoding:

import json

data = [{ 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}]

json = json.dumps (data)
print(json)

The above code execution results:

[{ "A": 1, "c": 3, "b": 2, "e": 5, "d": 4}]

Use JSON data format the output parameters so that:

>>> import json
>>>
>>> print(json.dumps({ 'a': 'Runoob', 'b': 7}, sort_keys = True, indent = 4, separators = ( ',', ':')))
{
    "a":"Runoob",
    "b":7
}
>>> 

python original type of the conversion table json type:

Python JSON
dict object
list, tuple array
str, unicode string
int, long, float number
True true
False false
None null

json.loads

json.loads JSON data for decoding. This function returns the field data type Python.

The following example shows how to decode JSON objects Python:

import json

jsonData = '{ "a": 1, "b": 2, "c": 3, "d": 4, "e": 5}';

text = json.loads (jsonData)
print(text)

The above code execution results:

{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

json type conversion table to the type of python:

JSON Python
object dict
array list
string unicode
number (int) int, long
number (real) float
true True
false False
null None

  
More Reference:

Top comments (0)