"Python advanced" 03, JSON

Source: Internet
Author: User

This section learns how to encode and decode JSON objects using the Python language.

The code here does not refer to character encoding, but rather translates the Python object into textual information that can be transmitted over the network or on other media.

I. INTRODUCTION of JSON

JSON: JAvaScript Object Notation (JavaScript object notation)

JSON is the syntax for storing and exchanging textual information. Similar to XML.

JSON is smaller, faster, and easier to parse than XML.

JSON uses JavaScript syntax to describe data objects, but JSON is still independent of language and platform. The JSON parser and the JSON library support many different programming languages. Currently very much dynamic (php,jsp,. NET) programming language supports JSON.


JSON instance
{"Sites": [{"Name": "Rookie Tutorial", "url": "Www.runoob.com"}, {"name": "Google", "url": "www.google.com"}, {"name": "Weibo", "url" : "Www.weibo.com"}]}

This sites object is an array that contains 3 site records (objects).

Python-like Dict


JSON syntax rules:

    • Data in name/value pairs

    • Data is separated by commas

    • Curly braces Save Object

    • Square brackets Save Array


Second, JSON module

In [4]: Import Jsonin [5]: Json.json.JSONDecoder json.dump json.load json. Jsonencoder json.dumps json.loads json.decoder json.encoder Json.scanner

Encode Encode a Python object as a JSON string
Decode

Decodes the encoded JSON string into a Python- like

Python and JSON support several structural transformations:

|  supports the following objects and types by default:      |       |  +-------------------+--------- ------+     |  | python             | JSON          |      |  +===================+===============+     |   | dict              |  object        |     |  +----- --------------+---------------+     |  | list, tuple        | array         |      |   +-------------------+---------------+     |  | str, unicode       | string        |      |  +-------------------+---------------+     |   | int, long, float  | number         |     |  +-------------------+---------------+      |  | True               | true          |      |  +-------------------+---------------+     |  |  false             | false          |     |  +-------------------+---------------+      |  | None               | null          |     |   +-------------------+---------------+

Case: There is a JSON file that saves user information and needs to parse the JSON into the user class.

user = Nametuple (' user ', [' name ', ' age ', ' gender ', ' phone ', ' mail ')

[[email protected] src]# cat text.json{"users": [{"Name": "XJ", "age": +, "gender": "Man", "Phone": "15711112222", "Mail": "[email protected]"}]}

Solution:

Parsing JSON as a dictionary, and then working with dictionaries

      using Object_hook

In [3]: ret = json.load (Open ("/tmp/src/text.json")) In [4]: retout[4]: {u ' Users ':  [{u ' age ':  25,   u ' gender ':  u ' man ',    u ' mail ':  u ' [ Email protected] ',    u ' name ':  u ' XJ ',    u ' phone ':  u ' 15711112222 '}] }in [5]: type (ret) out[5]: dictin [6]: ret.ret.clear        ret.items       ret.pop          ret.viewitemsret.copy        ret.iteritems    ret.popitem     ret.viewkeysret.fromkeys     ret.iterkeys    ret.setdefault  ret.viewvaluesret.get          ret.itervalues  ret.update      ret.has_ Key     ret.keYs        ret.values    in [7]: ret[' Users ']out[7]: [{u ' age ':  25,  u ' gender ':  u ' man ',   u ' mail ':  u ' [email  protected] ',   u ' name ':  u ' XJ ',   u ' phone ':  u ' 15711112222 '}]     in [16]: type (ret[' users ']) out[16]: listin [17]: ret[' users '][0]Out[17]:  {u ' age ':  25, u ' gender ':  u ' man ',  u ' mail ':  u ' [email protected] ',  u ' name ':  u ' XJ ',  u ' phone ':  u ' 15711112222 '} in [19]: ret[' users '][0][' age ']out[19]:  25


"Python advanced" 03, JSON

Related Article

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.