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!