我对Python非常陌生,所以如果这是一个简单的请求,请原谅我。
我有一个JSON文件,它有一个主索引(interfaces),其中包含许多变量,例如:
"interfaces": [{
"status": {
"ethernet": {
"string": "up",
"value": 1
}
},
"type": "ethernet",
}, {
"cell_info": {
"airplane_mode": false,
"capabilities": "0x00000000",
"carriers": {
"primary": {
"band": "B7",
"bandwidth": "20 MHz",
}
}
},我想要做的是将cell_info集中的所有信息放到一个CSV文件中。
我尝试使用在https://www.geeksforgeeks.org/convert-json-to-csv-in-python/上列出的方法,不幸的是,当interfaces下的信息以我想要的方式被解析时,cell info下的信息被解析的方式不同(可能是因为它是一个与interfaces的“根”组中列出的变量完全不同的变量集)。

下面是我一直在使用的代码。我能做些什么来关注cell info组下的数据吗?还是应该重新开始?
# Python program to convert
# JSON file to CSV
import json
import csv
# Opening JSON file and loading the data
# into the variable data
with open(r'C:\Users\chick\Desktop\Jsons\home\support\bcfiles\$$5liZwDzM-Interfaces.json') as json_file:
data = json.load(json_file)
interface_data = data['interfaces']
# now we will open a file for writing
data_file = open(r'C:\Users\chick\Desktop\Jsons\data_file.csv', 'w')
# create the csv writer object
csv_writer = csv.writer(data_file)
# Counter variable used for writing
# headers to the CSV file
count = 0
for iface in interface_data:
if count == 0:
# Writing headers of CSV file
header = iface.keys()
csv_writer.writerow(header)
count += 1
# Writing data of CSV file
csv_writer.writerow(iface.values())
data_file.close()发布于 2021-08-23 22:48:09
您只需访问"cell_info"密钥即可。尝试以下修改:
for iface in interface_data:
if "cell_info" not in iface:
continue
if count == 0:
# Writing headers of CSV file
header = iface["cell_info"] .keys() # access they keys of the inner dictionary at "cell_info"
csv_writer.writerow(header)
count += 1
# Writing data of CSV file
csv_writer.writerow(iface["cell_info"].values()) # access the values of the inner dictionary at "cell_info"https://stackoverflow.com/questions/68899775
复制相似问题