如何用Python提取JSON数据中的state与pvPower字段至独立文件?
Python提取JSON字段到独立文件的方法
实现步骤
- 解析目标JSON数据(支持直接定义或从文件读取)
- 提取指定字段的值
- 将字段内容分别写入独立文件
代码示例(直接使用内置JSON数据)
import json # 设备JSON数据 device_data = { "componentId": "SD1:1100047938", "componentType": "Device", "name": "WR50MS15-7938 (WR 33)", "product": "SB 5000TL", "productTagId": 9037, "pvPower": 886, "serial": "1100047938", "specWhOutToday": 3.0909803921568626, "specWhOutYesterday": 2.924313725490196, "state": 307, "totWhOutToday": 15764, "totWhOutYesterday": 14914 } # 提取state字段并写入state.txt with open('state.txt', 'w') as state_file: state_file.write(str(device_data['state'])) # 提取pvPower字段并写入pvPower.txt with open('pvPower.txt', 'w') as pv_file: pv_file.write(str(device_data['pvPower']))
从外部JSON文件读取数据的情况
如果JSON数据保存在device.json文件中,可使用以下代码:
import json # 读取外部JSON文件 with open('device.json', 'r') as data_file: device_data = json.load(data_file) # 写入state到文件 with open('state.txt', 'w') as state_file: state_file.write(str(device_data['state'])) # 写入pvPower到文件 with open('pvPower.txt', 'w') as pv_file: pv_file.write(str(device_data['pvPower']))
执行代码后,会在当前目录生成两个文件:
state.txt:内容为307pvPower.txt:内容为886
内容的提问来源于stack exchange,提问作者Sn0w3y
相关产品推荐
相关产品推荐

