Python interface automation 5-json data processing

Source: Internet
Author: User
Tags true true

Objective

Some post request parameters are in JSON format, mentioned in the previous second POST request, need to import JSON module processing.

Common interface return data is also JSON format, when we make judgments, often only need to extract a few of the key parameters on the line, this time we need JSON to parse the returned data.

I. Introduction to the JSON module

1.Json Introduction: Json, full name JavaScript Object Notation, is a lightweight data interchange format, commonly used in HTTP requests

2. You can use Help (JSON) to view the corresponding source code comment content

Encoding basic Python Object hierarchies::              >>> Import JSON         >>> json.dumps ([' foo ', {' Bar ': (' Baz ', None, 1.0, 2)}])         ' ["foo", {"bar": ["Baz", NULL, 1.0, 2]}] '          >>> print json.dumps ("\" Foo\bar ")        " \ "Foo\bar"         >>> Print json.dumps (U ' \u1234 ')          "\u1234"         >>> print json.dumps (' \ \ ')          "\"         >>> print json.dumps ({"C": 0 , "B": 0, "a": 0}, Sort_keys=true)         {"A": 0, "B": 0, "C": 0}    & nbsp;    >>> from Stringio import Stringio &NBsp;       >>> io = Stringio ()         > >> json.dump ([' Streaming API '], io)         >>> io.getvalue ()         ' ["Streaming API"] '

Second, Encode (Python->json)

1. First of all, why should encode,python inside bool value is true and False,json inside bool value is true and false, and case-sensitive, this is embarrassing, obviously is bool value.

The code written in Python, uploaded to JSON, is certainly not recognizable, so Python's code needs to be encode to become a JSON-recognizable data type.

2. For a simple example, the Dict type after Json.dumps () becomes str,true True,false becomes fasle

3. The following table of correspondence is crawled out of the source code of the JSON module. Python data class, after encode into JSON data type, the corresponding table is as follows      |  | python              | json          |      |  +===================+===============+      |  | dict                  | object        |      |  +-------------------+---------------+      |  | List, tuple          | array         |      |  +-------------------+---------------+      |  | STR, unicode      | string        |      |  +-------------------+---------------+      |  | int, long, float  | number        |      |  +-------------------+---------------+      |  | true                | true          |      |  +-------------------+---------------+      |  | false             | false         |      |  +-------------------+---------------+      |  | none              | null          |      |  +-------------------+---------------+

SAN, decode (Json->python)

1. With the third entry successful result: {"Success": true} as an example, what we really want to know is whether success this field returns TRUE or False

2. If output is in content byte, a string is returned: {"Success": true}, so it is inconvenient to get the result later.

3. If the JSON is decoded, the return is a dictionary: {u ' success ': True}, so as to obtain the following result, the dictionary to use the way to value: result2["Success"]

4. The same JSON data is converted into Python-identifiable data, and the corresponding table relationships are as follows

|  +---------------+-------------------+      |  | json               | python            |      |  +===============+===================+      |  | object             | dict              |      |  +---------------+-------------------+      |  | array               | list              |      |  +---------------+-------------------+      |  | string              | unicode           |      |  +---------------+-------------------+      |  | Number (int)     | int, long         |      |  +---------------+-------------------+      |  | Number (real)    | float             |      |  +---------------+-------------------+      |  | true                | true              |      |  +---------------+-------------------+      |  | false               | false             |      |  +---------------+-------------------+      |  | null                 | none              |      |  +---------------+-------------------+

Four, case analysis

1. For example, open the Express network: http://www.kuaidi.com/, search for a number, to determine whether its status has been signed

2. The implementation code is as follows

Five, reference code:

# Coding:utf-8 Import Requests
url = "http://www.kuaidi.com/index-ajaxselectcourierinfo-1202247993797-yunda.html" headers = {"User-agent": " mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) gecko/20100101 firefox/44.0 "} # Get method add a ser-agent to it.
s = requests.session () R = S.get (URL, headers=headers,verify=false) result = R.json () data = result["Data" # Get the contents of data Print data print data[0] # get data in the top there is a get_result = data[0][' context '] # get the signed status print Get_result
if u "signed" in Get_result:print "Courier receipt successful" Else:print "not Signed"

Python interface automation 5-json data processing

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.