gpt4 book ai didi

从 JSON 文件中提取数据的 Python 程序

转载 作者:行者123 更新时间:2023-11-30 23:13:26 25 4
gpt4 key购买 nike

我有一个包含数据元数据的Python文件。我在该文件上使用以下程序。

import requests
from lxml import html
import json

with open("tmp.json") as json_file:
json_data = json.load(json_file)
print(json_data)

在输出中,我在 JSON 文件中同时获取了 datametadata。我只想提取数据部分。我该怎么做?

我的 JSON 文件的示例结构如下。

 "data": [
{
"AvInterval": null,
"DelInterval": null,
"ntsGenerated": null,
"ntsGenerated": null,
"Metric": "Intervals",
"Total": 23
},
{
"AvInterval": null,
"DelInterval": null,
"ntsGenerated": null,
"ntsGenerated": null,
"Metric": "CPU",
"Total": 47
},
],
"metadata": {
"columns": [
{
"Caption": "Metric",
"Field": "Metric",
"Type": "string",
"Width": "*"
},
{
"Caption": "Total",
"Field": "Total",
"Type": "long",
"Width": "*"
},
]

}

我想从上述文件中删除元数据,并将数据分成不同的部分,并将每个单独的部分写入一个文件中。

最佳答案

如果你想将数据分割成不同的部分并将每个部分写入自己的文件中,你可以这样做:

with open("tmp.json") as json_file:
json_data = json.load(json_file)
for i, data_item in enumerate(json_data['data']):
fname = 'data_%s' % i
with open(fname, 'w') as outfile:
json.dump(data_item, outfile)

关于从 JSON 文件中提取数据的 Python 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29338468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com