一、先来看下json格式的数据如何取出某个字段,列如:我要取出里面的 lcate和guid,输出的样式要是:
1;904eff52277f403b89f6410fe2758646.11
2;58457f60eca64025bc43a978f9c98345.16
3;a0f907f9dc8b40f689b083f3eba7228b.16
4;eb75d929455e468bb712e7bc2025d11a.16
json_data = """{
"favourite":{
"bkmrk":{
"id1490843709594066":{
"guid":"904eff52277f403b89f6410fe2758646.11",
"lcate":"1"
},
"id1490843712805183":{
"guid":"58457f60eca64025bc43a978f9c98345.16",
"lcate":"2"
},
"id149084371467327":{
"guid":"a0f907f9dc8b40f689b083f3eba7228b.16",
"lcate":"3"
},
"id1490843716295393":{
"guid":"eb75d929455e468bb712e7bc2025d11a.16",
"lcate":"4"
}
}
}
}"""
那么我们写的代码很简单:
如下:
import json
json_data = """{
"favourite":{
"bkmrk":{
"id1490843709594066":{
"guid":"904eff52277f403b89f6410fe2758646.11",
"lcate":"1"
},
"id1490843712805183":{
"guid":"58457f60eca64025bc43a978f9c98345.16",
"lcate":"2"
},
"id149084371467327":{
"guid":"a0f907f9dc8b40f689b083f3eba7228b.16",
"lcate":"3"
},
"id1490843716295393":{
"guid":"eb75d929455e468bb712e7bc2025d11a.16",
"lcate":"4"
}
}
}
}"""
data = json.loads(json_data)
for v in data['favourite']['bkmrk'].values():
print("%s;%s" % (v['lcate'], v['guid']))
二、下面再来说一下,如何把dict格式写成json格式的文件夹中:
import json
def write_to_json(ips):
with open('proxies.json', 'w', encoding='utf-8') as f:
json.dump(ips, f, indent=4)
ips = [{'ip':'12.234.232.43', 'port':8978, 'type':'https'},{'ip':'45.234.232.43', 'port':2378, 'type':'https'},{'ip':'17.883.232.43', 'port':978, 'type':'https'}]
write_to_json(ips)