简体   繁体   English

将数据从 json 转储到 csv

[英]Dumping data from json to csv

I have 100 json file, each json file contains following kind of dict format.我有 100 个 json 文件,每个 json 文件包含以下类型的 dict 格式。

I would like to create a csv file and dump only我想创建一个 csv 文件并只转储

{
  "label": "image",
  "confidence": 1.0
}

this data into csv file into prediction column along with json file name.将此数据与 json 文件名一起放入 csv 文件到预测列中。 How would I do it?我该怎么做?

Assuming you know already how to read the json file as dictionary in python.假设您已经知道如何在 python 中将 json 文件作为字典读取。 You could do this.你可以这样做。

import pandas as pd
json_data =  {   "predictions": [
        {
          "label": "empty",
          "confidence": 1.0
        },
        {
          "label": "filled",
          "confidence": 9.40968867750501e-25
        },
        {
          "label": "no-checkbox",
          "confidence": 1.7350328516351668e-28
        }  
       ] 
    }

output_df = pd.DataFrame(json_data['predictions'])
print(output_df)
         label    confidence
0        empty  1.000000e+00
1       filled  9.409689e-25
2  no-checkbox  1.735033e-28

rowIf I understand ok what you want, you want to get only the first "item" on predictions list, from multiple files on some path. rowIf 我明白你想要什么,你只想从某个路径上的多个文件中获取预测列表中的第一个“项目”。 And then put all this as rows on a csv.然后将所有这些作为行放在 csv 上。 So you can do something like:因此,您可以执行以下操作:

import csv
import json
from os import listdir
from os.path import isfile, join

path = 'path/to/dir'
result = []
for file_name in listdir(path):
    with open(join(path, file_name), 'r') as f:
        data = json.load(f)
        first = data['predictions'][0]
        result.append([first['label'], first['confidence']])

with open('path/to/result.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerow(['label', 'confidence']) # Comment this line if you dont want a header row
    writer.writerows(result)

Replacing 'path/to/dir' with the path of the json files directory, and 'path/to/result.csv' with the path to the result csv file.'path/to/dir'替换为 json 文件目录的路径,将'path/to/result.csv'替换为结果 csv 文件的路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM