You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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:内容为307
  • pvPower.txt:内容为886

内容的提问来源于stack exchange,提问作者Sn0w3y

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 07:10:32