Python Operation JSON

Source: Internet
Author: User
Tags python list

Concept

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.

JSON (JavaScript Object Notation): A lightweight data interchange format that is easier to read and write than XML, is easy to parse and generate, and JSON is a subset of JavaScript.

Python2.6 started adding JSON modules without additional download, and the Python JSON module serialization and deserialization process is encoding and decoding , respectively.

encoding: Converts a Python object encoding into a JSON string
decoding: Converting JSON format string decoding to Python object
For simple data types (string, Unicode, int, float, list, tuple, dict), they can be processed directly.

The Json.dumps method is encoding for simple data types:
import jsondata = [{‘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)}] #python的dict类型的数据是没有顺序存储的JSON: [{"a":"A","c":3.0,"b":[2,4]}]  

The output of JSON is similar to data, except for some subtle changes such as Python's tuple type becoming an array of JSON, the code conversion rules for Python to JSON are:

The Json.loads method handles decoding (decoding) conversions of simple data types
import jsondata = [{‘a‘:"A",‘b‘:(2,4),‘c‘:3.0}]  #list对象data_string = json.dumps(data)print "ENCODED:",data_stringdecoded = json.loads(data_string)print "DECODED:",decodedprint "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‘>DECODED: <type ‘list‘>

During decoding, the JSON array is eventually converted to the Python list instead of the original tuple type, and the JSON-to-Python decoding rules are:

The humanistic care of JSON

Encoded JSON-formatted strings are compact output, and there is no order, so the dumps method provides some optional parameters to make the output format more readable, such as sort_keys telling the encoder to sort by dictionary (A to Z) output.

import jsondata = [ { ‘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}

indentParameters are indented according to the data format and are clearer to read:

import jsondata = [ { ‘a‘:‘A‘, ‘b‘:(2, 4), ‘c‘:3.0 } ]print ‘DATA:‘, repr(data)print ‘NORMAL:‘, json.dumps(data, sort_keys=True)print ‘INDENT:‘, json.dumps(data, sort_keys=True, indent=2)

Output:

DATA: [{‘a‘: ‘A‘, ‘c‘: 3.0, ‘b‘: (2, 4)}]NORMAL: [{"a": "A", "b": [2, 4], "c": 3.0}]INDENT: [  {    "a": "A",    "b": [      2,      4    ],    "c": 3.0  }]

separatorsThe function of the parameter is to remove , , : The following space, from the above output can be seen ",:" There is a space behind, which is to beautify the effect of the output, but in the process of transmitting data, the more streamlined the better, redundant things all removed, Therefore, the separators parameter can be added:

import jsondata = [ { ‘a‘:‘A‘, ‘b‘:(2, 4), ‘c‘:3.0 } ]print ‘DATA:‘, repr(data)print ‘repr(data)             :‘, len(repr(data))print ‘dumps(data)            :‘, len(json.dumps(data))print ‘dumps(data, indent=2)  :‘, len(json.dumps(data, indent=2))print ‘dumps(data, separators):‘, len(json.dumps(data, separators=(‘,‘,‘:‘)))

Output:

DATA: [{‘a‘: ‘A‘, ‘c‘: 3.0, ‘b‘: (2, 4)}]repr(data)             : 35dumps(data)            : 35dumps(data, indent=2)  : 76dumps(data, separators): 29

skipkeysparameter, in the encoding process, the Dict object's key can only be a string object, and if it is another type, the exception that is thrown during the encoding process ValueError . skipkeysYou can skip the processing of those non-string objects as keys.

import jsondata= [ { ‘a‘:‘A‘, ‘b‘:(2, 4), ‘c‘:3.0, (‘d‘,):‘D tuple‘ } ]try:    print json.dumps(data)except (TypeError, ValueError) as err:    print ‘ERROR:‘, errprint print json.dumps(data, skipkeys=True)

Output:

ERROR: keys must be a string[{"a": "A", "c": 3.0, "b": [2, 4]}]


http://liuzhijun.iteye.com/blog/1859857

Python Operation 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.