【问题标题】:multiple json to csv using pandas python使用pandas python将多个json转换为csv
【发布时间】:2021-04-26 20:53:14
【问题描述】:

尝试将多个 json 文件转换为 1 个 csv 文件
尝试了2种方法,
第一个使用熊猫, 第二个使用 json 和 csv 编写器
关于我的 json

keys are unordered and some keys are different in every file

使用编写器编写代码

file_list=os.listdir('output')
count = 0
for file in file_list:
    dict={}
    file_path = "output/" + file
    with open(file_path,'r') as f:
        jsonData=json.load(f)
        datafile=open('data.csv','a')
        csv_writer = csv.writer(datafile)
        if count == 0:
            header = jsonData.keys()
            csv_writer.writerow(header)
            count += 1
            csv_writer.writerow(jsonData.values())
        if count == 1:
            csv_writer.writerow(jsonData.values())

        datafile.close()

问题

bcoz my data is unordered and different keys so in my csv file wrong value is coming under wrong header

使用 Pandas 编写代码

for file in file_list:
    dict={}
    file_path = "output/" + file
    with open(file_path,'r') as f:
        jsonData=json.load(f)
        for j in jsonData:


            dict.update({j:[jsonData[j]]})
        df=pd.DataFrame(dict)
        df.to_csv("hello.csv")

问题

i dont know how to append in pandas 
so this is showing only 2 rows bcoz of my last json file i guess

在我的 json 中

【问题讨论】:

  • 每个 json 文件是否应该在输出中占一行?您能否提供一两个简短的示例 json 文件,甚至可能是所有可能键的列表,它们应该出现在 csv 输出中?
  • 标头Solutions, account_number ,actual_reading_current, actual_reading_previous address, amount_due,$7.90 72xxx06,,,, 16839,,, 16586 ,,, T B FAIR LAWN BORO NJ 07410 ,,,48.1
  • 这是您想要的 csv 文件的标题?你能否也给我一个虚拟的json文件来测试?请使用文件共享服务或更改您的原始帖子,cmets 不允许大量格式化。
  • @ClF3 添加 json 数据

标签: python json pandas csv


【解决方案1】:

试试这个代码:

import pandas as pd
import json
import pathlib

data_path = pathlib.Path('.')
keys = ['Solutions', 'account_number', 'actual_reading_current','actual_reading_previous', 'address', 'amount_due']
dat = dict([(k, []) for k in keys])

for jfile in data_path.glob('*.json'):
    with jfile.open('r') as ifile:
        json_data = json.load(ifile)
    for key in keys:
        dat[key].append(json_data[key][0] if key in json_data else None)

result = pd.DataFrame.from_dict(dat)
result.to_csv('result.csv')

我首先定义一个包含我想要的列的字典。 然后我读入 json 文件并将它们作为行附加到字典中。

请注意,我必须编辑您的 json 文件,其中一个缺少结束引号,我必须用双引号替换单引号。

【讨论】:

  • 这个错误来了dat[key].append(json_data[key][0] if key in json_data else None) TypeError: 'float' object is not subscriptable
  • 有趣。是否有可能某些 json 文件的结构不同,例如并非所有值都在列表中?如果是这种情况,您可以让所有 json 文件使用相同的格式,或者在主循环中检查 json_data[key] 是否是一个列表。
  • 我上面显示的好的数据是我通过我的代码将它编辑到列表中,,,,值不在我的 json 中的列表中,它们是普通字符串
  • 第一次循环后的内部数据\{' Solutions': ['$'], 'account_number': [], 'actual_reading_current': [], 'actual_reading_previous': [], 'address': [], 'amount_due': [], 'average_supply': [], 'rate': [], 'total_amount_debt': [], 'total_electric_charge': [], 'total_electric_delivery_charge': [], 'total_electricity_used': []}
  • 我不会改变我的答案,而你的 json 格式保留在原始帖子中。但要使用不同的格式,请将 'json_data[key][0] if key in json_data else None' 更改为 'json_data.get(key, None)'。您不再需要从数组中取出值,只需获取键,如果键不存在,则返回 None。
猜你喜欢
  • 2017-09-12
  • 2019-03-15
  • 2017-06-10
  • 2021-12-28
  • 2018-11-06
  • 2022-01-26
  • 1970-01-01
  • 2018-09-16
  • 1970-01-01
相关资源
最近更新 更多