目录
1 JSON结构
2 解析JSON
1 JSON结构
▲JSON结构
{
"name" : "Chuck",
"phone" : {
"type" : "intl",
"number" : "+1 734 303 4456"
},
"email" : {
"hide" : "yes"
}
}
▲XML结构
<person>
<name>Chuck</name>
<phone type="intl">
+1 734 303 4456
</phone>
<email hide="yes" />
</person>
▲JSON与XML的区别:
XML可以在元素中添加attribute属性,如<phone type="intl">?,而JSON中只有key-value对;
XML中有顶级元素<person>,而JSON最外层为{}
2 解析JSON
▲利用JSON库解析
▲示例一:
import json
data = '''
{
"name" : "Chuck",
"phone" : {
"type" : "intl",
"number" : "+1 734 303 4456"
},
"email" : {
"hide" : "yes"
}
}'''
info = json.loads(data)###json.loads解析JSON
print(info)
print(type(info))
print('User count:', len(info))
print('Name', info['name'])
print('phone number', info['phone']['number'])
▲示例二:?
import json
data = '''
[
{ "id" : "001",
"x" : "2",
"name" : "Chuck"
} ,
{ "id" : "009",
"x" : "7",
"name" : "Brent"
}
]'''
info = json.loads(data)###json.loads解析JSON
print(info)###info为包含两个字典的列表
print(type(info))###list
print('User count:', len(info))
for item in info:###列表循环输出
print('Name', item['name'])
print('Id', item['id'])
print('Attribute', item['x'])
|