Python tutorial python JSON

Source: Internet
Author: User

Python JSON

In this section we will show you how to encode and decode JSON objects using the Python language.

Environment configuration

Before using Python to encode or decode JSON data, we need to install the JSON module first. 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

Describe


Encode to encode a Python object as a JSON string

Decode decoding encoded JSON strings to Python objects

Encode

The Python encode () function encodes a Python object into a JSON string.

Grammar

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

Instance

The following example encodes an array into JSON-formatted data:

#!/usr/bin/pythonimport Demjsondata = [{' A ': 1, ' B ': 2, ' C ': 3, ' d ': 4, ' E ': 5}]json = Demjson.encode (data) print Json

The result of the above code execution is:

[{"A": 1, "B": 2, "C": 3, "D": 4, "E": 5}]

Decode

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

Grammar

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 result of the above code execution is:

{u ' a ': 1, U ' C ': 3, U ' B ': 2, U ' E ': 5, U ' d ': 4}

The above is the "Python tutorial" python json content, more relevant content please follow topic.alibabacloud.com (www.php.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.