Python operation JSON (i)

Source: Internet
Author: User
Tags python list

Python Operation JSON

JSON syntax rules:
Data in name/value pairs
Data is separated by commas
Curly braces Save Object
Square brackets Save Array
A JSON string is essentially a string, expressed in single quotation marks

Writing format for JSON data
Name-value pairs, including the Name field (in double quotes), followed by a colon, and then the value:
"Name": "Zhangsan" equivalent to name = "Zhangsan"
JSON value
Value can be
Number (integer or floating point)
string (enclosed in double quotes)
Logical value (TRUE or FALSE)
Array (in square brackets)
Object (in curly braces)
Null
JSON object
The JSON object is in curly braces,
{"Name": "Zhangsan", "Age": 20}
Equivalent name= "Zhangsan" age = 20

JSON array
The JSON array is in brackets, and the array can contain multiple objects
{
"Employees": [
{"FirstName": "John", "LastName": "Doe"},
{"FirstName": "Anna", "LastName": "Smith"},
{"FirstName": "Peter", "LastName": "Jones"}
]
}
Employees is an array that contains three objects

Code Json.dumps ()
Encodes a Python object into a JSON string,

Python list converted to JSON array

>> Json.dumps (["a"])
' [1, 2, 3, ' a '] '

Python string converted to JSON string

>> json.dumps ("abc123")
' "abc123" '

Python tuples converted to JSON arrays

>> Json.dumps (("A", "B"))
' [1, 2, 3, ' A ', ' B '] '

Python dictionary converted to JSON object

>> Json.dumps ({1: "A", 2: "B", 3: "C"})
' {' 1 ': ' A ', ' 2 ': ' B ', ' 3 ': ' C '} ' #注意1, 2, 3 are enclosed in double quotes because the JSON name must be double-quoted

Python numbers (long) are converted to JSON numbers

>> Json.dumps (13L)
' 13 '

Python numbers (int) are converted to JSON numbers

>> Json.dumps (13)
' 13 '

Python's Unicode string converted to JSON string

>> json.dumps (U "AbC")
' "AbC" '

True of Python converted to JSON

>> Json.dumps (True)
' True '

False of Python converted to JSON

>> Json.dumps (False)
' False '

Python none converted to JSON null

>> Json.dumps (None)
' NULL '

>> type (json.dumps ("abc")) #json本质上是一个字符串
<type ' str ' >

How to tell if a JSON is legal?
With try except
Try
Json.loads (' abc ')
Except Exception,e:
Print E
Else
print "OK"

Json.dumps () function parameter application
Sort_keys
Whether to sort by key, Sort_keys = True ascending sort

#coding =utf-8
Import JSON
data = [{' A ': ' A ', ' B ':(2, 4), ' C ': 3.0}]
Print Json.dumps (data)
Print json.dumps (data, sort_keys=true)

Indent
Sets the number of spaces the parameter indents display. The indent display makes it clearer to read.
#coding =utf-8
Import JSON
data = [{"A": "A", "B": [2, 4], "C": 3.0}]
Print json.dumps (data, sort_keys=true, indent=3)

Separators
The function of the parameter is to remove the comma "," and semicolon ":" After the space, from the output of the above can see "," and ":" followed by a space, 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 to compress the transmitted JSON string. The parameter is in the tuple format
Import JSON
data = [{"A": "A", "B": [2, 4], "C": 3.0}]
Print Len (json.dumps (data))
Remove the encoded JSON string, and: Trailing spaces
Print Len (json.dumps (Data, separators= (', ', ': ')))

Skipkeys
In the encoding process, the Dict object's key can only be the basic data type (Str,unicode,int,long,float,bool,none), and if it is a different type, it will throw a TypeError exception during the encoding process. Skipkeys can skip the handling of keys that are not string objects, that is, do not handle
Import JSON
Data= [{' A ': ' A ', ' B ':(2, 4), ' C ': 3.0, (+): ' D tuple '}]
Print U "do not set Skipkeys parameter"
Try:
Res1 = json.dumps (data) #skipkeys参数默认为False时
Except Exception, E:
Print E

Print U "set skipkeys parameter"
Print json.dumps (data, skipkeys=true)

Python operation JSON (i)

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.