python - 在python中将带有子字段的Json转换为CSV
问题描述
我有一个带有示例 JSON 输出的文件,如下所示: jsonoutput.txt 文件:
[{"fruit": "orange", "id":1, "countries": ["Portugal"], "color": "Orange"}
{"fruit": "apple", "id":2, "countries": ["Portugal"], "color": "red"}]
我需要输出 csv 作为(excel 文件):
fruit id countries color
orange 1 Portugal Orange
apple 2 Spain red
现在,我得到的水果 id 国家颜色为橙色 1 [u'Portugal'] Orange apple 2 [u'Spain'] red
如何从列国家/地区中删除 [] 、 u 和 '' ?
print (json.dumps(fruits))
--在json输出中给我
这是我尝试将 json 转换为 xlsx 的内容:
data= tablib.Dataset(headers=('Fruit','id','Countries','Color'))
importfile = 'jsonoutput.txt'
data.json = open(importfile. 'r').read()
data_export = data.export('xlsx')
with open('output.xlsx','wb') as f:
f.write(data_export)
f.close()
解决方案
你可以使用pandas.io.json.json_normalize
import pandas as pd
from pandas.io.json import json_normalize
d = [
{"fruit": "orange", "id":1, "countries": ["Portugal"], "color": "Orange"},
{"fruit": "apple", "id":2, "countries": ["Portugal"], "color": "red"}
]
df = pd.concat([json_normalize(d[i]) for i in range(len(d))], ignore_index=True)
df['countries'] = df['countries'].str.join(' ')
fruit id countries color
0 orange 1 Portugal Orange
1 apple 2 Portugal red
要将其保存为.xlsx
文件,请使用:
df.to_excel('filename.xlsx', index=False)
编辑:
json_normalize
是将半结构化 JSON 数据标准化为平面表的函数。
我现在实际上意识到我的代码可以简化为:
df = json_normalize(d) # no need for `pd.concat`
### Output:
# fruit id countries color
# 0 orange 1 ['Portugal'] Orange
# 1 apple 2 ['Portugal'] red
为了[]
从countries
列中删除,我使用pandas.Series.str.join
了pandas
' 相当于 Python 的str.join
.
它是必需的,因为最初countries
列是包含元素的列表
df['countries'] = df['countries'].str.join(' ')
countries
加入项目后,列不再是列表:
fruit id countries color
0 orange 1 Portugal Orange
1 apple 2 Portugal red
推荐阅读
- docker - 无法从应用容器连接到 redis 容器
- excel - 从一个工作簿复制工作表并粘贴到另一个工作簿
- angular - 使用 amcharts4 编译 Angular 8 CLI 项目时出现问题
- r - 用 VCF 文件中的 DNA 字母替换数字基因型代码
- spring - spring cloud gateway exception Illegal character in authority at index error
- node.js - 忽略文件夹内的白名单文件夹
- bash - 循环浏览术语列表和批量重命名文件
- laravel - 如何从两个表中获取匹配的数据?
- python - 从多个 JSON 文件构造 DataFrame
- typescript - 如何使用多态性来隐藏接口的属性?