Python instance 27 [JSON]

Source: Internet
Author: User

1. JSON

 

Http://json.org/

JSON Syntax:

1) string: value can be regarded as the smallest unit of JSON. JSON is composed of a collection of string: value, where value can be nested with string: value;

2) string is a unicode string enclosed by double quotation marks. special characters must be escaped;

3) value can be string: value, array, String, number, true, false, or null;

 

One instance:

{"Firstname": "John", "lastname": "Smith", "adress": {"streetaddress": "21 2nd Street", "city ": "New York", "State": "NY", "postalcode": 10021}, "phonenumbers": ["212 555-1234", "646-555"]

}

 

Python and JSON

 

3. Python JSON Module

Import JSON

Teststr ='''
{
"Firstname": "John ",
"Lastname": "Smith ",
"Adress ":{
"Streetaddress": "21 2nd Street ",
"City": "New York ",
"State": "NY ",
"Postalcode": 10021
},
"Phonenumbers ":[
"212 555-1234 ",
"646 555-4567"
]
}
'''

#Deserialize S (a STR or Unicode instance containing a JSON document) to a python object.
OBJ = JSON. Loads (teststr)

Print ( " Firstname: " + OBJ [ " Firstname " ])
Print ( " City: " + OBJ [ " Adress " ] [ " City " ])
Print ( " Phonenumbers: " + STR (OBJ [ " Phonenumbers " ])

#Serialize OBJ to a JSON formatted Str.
STR = JSON. dumps (OBJ, indent = 2)
Print(STR)

The output:
Firstname: John
City: New York
Phonenumbers: [U ' 212 555-1234 ' , U ' 646 555-4567 ' ]
{
" Lastname " : " Smith " ,
" Phonenumbers " :[
" 212 555-1234 " ,
" 646 555-4567 "
],
" Adress " :{
" Postalcode " 10021,
" City " : " New York " ,
" Streetaddress " : " 21 2nd Street " ,
" State " : " NY "
},
" Firstname " : " John "
}

Complete!

 

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.