Python中将复杂json格式的数据提取value值的方法
Python的json有两种方法:
edcode:decode:
当转化为字典类型时,取出数据时需要用到for循环进行遍历
下面是三个例子:
1、读取txt文件,其实就是string类型数据,获取值
txt文件内容如下:
2、 字典格式的数据,获取值
3、非正规json格式数据,取出值items = { "iot": "Ammeter", "ite": { "Power": { "value": "on", "time": 1510799670074 } }
或者是这样的形式:
items = {
"iot": "Ammeter",
"ite": {
"Power": {
"value": "on",
"time": 1510799670074
}}}
一、loads使用:
1、首先使用json加载字符串,然后取出value值
import json
items = '''{ "iot": "Ammeter", "ite": { "Power": [{ "value": "on", "time": 1510799670074 },{ "value": "off", "time": 1115464362163 }]} }'''
items = json.loads(items)
items1 = items["ite"]
items2 = items["ite"]['Power']
print(items1)
print(items2)
for item in items1:
print(item)
print(items1[item])
for item in items2:
print(item['value'])
输出:
{'Power': [{'value': 'on', 'time': 1510799670074}, {'value': 'off', 'time': 1115464362163}]}
[{'value': 'on', 'time': 1510799670074}, {'value': 'off', 'time': 1115464362163}]
Power
[{'value': 'on', 'time': 1510799670074}, {'value': 'off', 'time': 1115464362163}]
on
off
2、下列的标准json格式,取出count的值
page = html_str['data']['page']['count']
print(page)
输出:
460313
二、dumps使用
import json
items = '''{"iot":"Ammeter", "ite": { "Power": { "value": "on", "time": 1510799670074 } } }'''
items = json.dumps(items,ensure_ascii=True,indent=10)
print(items)
输出结果:
{
"iot": "Ammeter",
"ite": {
"Power": {
"value": "on",
"time": 1510799670074
}
}
}
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· 分享4款.NET开源、免费、实用的商城系统
· 解决跨域问题的这6种方案,真香!
· 5. Nginx 负载均衡配置案例(附有详细截图说明++)
· Windows 提权-UAC 绕过
2021-03-16 webdriver中元素查找常用方法