现在的位置: 首页 > 综合 > 正文

python实例27[json]

2011年05月13日 ⁄ 综合 ⁄ 共 1282字 ⁄ 字号 评论关闭

一 Json

 

json语法:

1) string:value 可以看做是json的最小单位,json由string:value的集合组成,其中value中可以嵌套string:value;

2) string为双引号包围的unicode字符串,特殊符号需要\来转义;

3) value可以为string:value,array,string,number,true,false,null;

 

一个实例:

{
 "firstName":"John",
 "lastName" :"Smith",
 "adress":{
  "streetAddress":"21 2nd Street",
  "city":"New York",
  "state":"NY",
  "postalCode":10021
  },
 "phoneNumbers":[
  "212 555-1234",
  "646 555-4567"
  ]

}  

 

二 python 与 json

 

三 python的json模块

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"
}

完!

 

抱歉!评论已关闭.