[python tutorial] Python JSON

黄舟
Release: 2016-12-24 15:30:43
Original
1071 people have browsed it

Python JSON

In this chapter we will introduce how to use Python language to encode and decode JSON objects.

Environment configuration

Before using Python to encode or decode JSON data, we need to install the JSON module first. We will download Demjson and install this tutorial:

$tar xvfz demjson-1.6.tar.gz
$cd demjson-1.6
$python setup.py install
Copy after login
E

JSON function


Function

Description


Encode encodes the Python object into a JSON string

Decode and decoded the coded JSON string to Python to Python Object

encode

Python encode() function is used to encode Python objects into JSON strings.

Syntax

demjson.encode(self, obj, nest_level=0)
Copy after login

Example

The following example encodes an array into JSON format data:

#!/usr/bin/python
import demjson

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

json = demjson.encode(data)
print json
Copy after login

The execution result of the above code is:

[{"a":1,"b":2,"c":3,"d":4,"e":5}]
Copy after login

decode

Python can use the demjson.decode() function to decode JSON data. This function returns the data type of the Python field.

Grammar

demjson.decode(self, txt)
Copy after login

Example

The following example shows how Python decodes JSON objects:

#!/usr/bin/python
import demjson

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

text = demjson.decode(json)
print  text
Copy after login

The execution result of the above code is:

{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4}
Copy after login

The above is the content of [python tutorial] Python JSON. For more related content, please pay attention to PHP Chinese Net (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template