Python's JSON module

Source: Internet
Author: User


# # 0x00 introduction:

If we are going to pass objects between different programming languages, we have to serialize the object into a standard format, such as xml, but the better way is to serialize it to json, because JSON represents a string that can be read by all languages, easily stored to disk, or transmitted over a Network. JSON is not only a standard format, but also faster than xml, and can be read directly in the Web page, very convenient.


Serialization (serialization): converts the state information of an object into a process that can be stored or transmitted over a network, in the form of json, xml, and so On. Deserialization is the state of the deserialized object that is read from the storage area (JSON,XML) and Re-created.


# # 0x01 Common functions:

# # # Json.dumps method for simple data type encoding


Encoding: converts a Python object encoding into a JSON string

Decoding: converting JSON format string decoding to Python object


Import JSON
data = [{' a ': ' a ', ' b ':(2,4), ' C ': 3.0}] #list对象
Print "data:", repr (data)

data_string = Json.dumps (data)
Print "JSON:", data_string

Output:

DATA: [{' a ': ' a ', ' C ': 3.0, ' B ':(2,4}]
JSON: [{"a": "a", "c": 3.0, "b": [2,4]}]

# # # Json.loads method handles decoding (decoding) conversions of simple data types

You can use the loads method to convert a JSON string into a python object.

Import JSON
data = [{' a ': ' a ', ' b ':(2,4), ' C ': 3.0}] #list对象

data_string = Json.dumps (data)
Print "encoded:", data_string

decoded = Json.loads (data_string)
Print "decoded:", decoded

Print "ORIGINAL:", type (data[0][' b '))
Print "decoded:", type (decoded[0][' b '))

Output:

Encoded: [{"a": "a", "c": 3.0, "b": [2, 4]}]
Decoded: [{u ' a ': u ' a ', u ' c ': 3.0, u ' b ': [2, 4]}]
ORIGINAL: <type ' tuple ' >


# # # Sort_keys is to tell the encoder to sort by dictionary (a to Z) output,



Import JSON
data = [{' a ': ' a ', ' b ':(2, 4), ' C ': 3.0}]
print ' Data: ', repr (data)
unsorted = Json.dumps (data)
print ' JSON: ', json.dumps (data)
print ' SORT: ', json.dumps (data, Sort_keys=true)

Output:

DATA: [{' a ': ' a ', ' C ': 3.0, ' b ': (2, 4)}]
JSON: [{"a": "a", "c": 3.0, "b": [2, 4]}]
SORT: [{"a": "a", "b": [2, 4], "c": 3.0}

The indent parameter is indented according to the data format and is read more clearly:

print ' INDENT: ', json.dumps (data, sort_keys=true, indent=2)

# # JSON format string written to the file stream

Import JSON
Import Tempfile

f = tempfile. Namedtemporaryfile (mode= ' w+ ')
F.write (' [{"a": "a", "c": 3.0, "b": [2, 4]}] ')
F.flush ()
F.seek (0)

Print Json.load (f)

Output:

[{u ' a ': u ' a ', u ' c ': 3.0, u ' b ': [2, 4]}]


# # 0x03 Basic case:

Case 1,

Import JSON
Js=json.loads (' {' "json": "you are my, hello"} ')
Print Json.dumps (js)
Print Json.dumps (js,ensure_ascii=false)

Case 2,

Import JSON
Js=json.loads (' {' "json": "you are my, hello"} ')
Print Json.dumps (js,encoding= "GB2312")
Print Json.dumps (js,encoding= "utf-8")

Case 3,

Import JSON
s = ' [{"name": "bird's nest", "point": {"lat": "39.990", "lng": "116.397"}, "desc": "olympic home"},{"name": "peking University table tennis hall", "point": {"lat": " 39.988 "," LNG ":" 116.315 "}," desc ":" Table Tennis competition Venue "},{" name ":" Beijing Worker Stadium "," Point ": {" lat ":" 39.930 "," LNG ":" 116.446 "}," desc ":" Football match Venue "}] '
Print Type (s)
Locations = Json.loads (s)
Print Type (locations)
#注: Read is the method of json-py.py and minijson.py, and python2.6 started with the Lib library with simplejson.py, which has no read method, but load/loads
The object after print str (len (LOCATIONS)) #因为json. load () is dict type!
For location in Locations:
Print location["name"]
Print location["point" ["lat"]

Case 4,

Import JSON
Json_string= ' {"first_name": "Guido", "last_name": "russum"} '
Print json_string
Print Type (json_string)
Parsed_json=json.loads (json_string)
Print Parsed_json
Print Type (parsed_json)
Print parsed_json[' last_name ']
Print Json.dumps (json_string)
print json.loads (json_string)

Python's JSON module

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.