[Python Tutorial] PythonJSON

Source: Internet
Author: User
This section describes how to use Python to encode and decode JSON objects.

Python JSON

This section describes how to use Python to encode and decode JSON objects.

Environment configuration

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

$tar xvfz demjson-1.6.tar.gz$cd demjson-1.6$python setup.py install

JSON Functions


Function

Description


Encode encodes a Python object into a JSON string

Decode decodes the encoded JSON string into a Python object

Encode

The Python encode () function is used to encode a Python object into a JSON string.

Syntax

demjson.encode(self, obj, nest_level=0)

Instance

The following example encodes arrays into JSON data:

#!/usr/bin/pythonimport demjsondata = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]json = demjson.encode(data)print json

The code execution result is:

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

Decode

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

Syntax

demjson.decode(self, txt)

Instance

The following example shows how Python decodes a JSON object:

#!/usr/bin/pythonimport demjsonjson = '{"a":1,"b":2,"c":3,"d":4,"e":5}';text = demjson.decode(json)print  text

The code execution result is:

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

The above is the python JSON content of the [Python Tutorial]. For more information, see The PHP Chinese website (www.php1.cn )!


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.