python - 从 JSON 写入 CSV,只导入给定的键
问题描述
我有 JSON 报告不同的值,我只想导入 csv 中的一些键。我尝试了两种方法,但都给我带来了一些问题。起初,我试过这个:
`import os,json
import glob
import csv
# Place your JSON data in a directory named 'data/'
src = "MYPATH"
data = []
json_pattern = os.path.join(src, '*.json')
# only json
files = glob.glob(json_pattern, recursive=True)
# Loop through files
for single_file in files:
with open(single_file, 'r') as f:
json_file = json.load(f)
try:
data.append([
json_file['name1'],
json_file['name2'],
json_file['name3'],
json_file['name4'],
])
except KeyError:
continue
# Add headers
data.insert(0, ['title_1', 'title_2', 'title_3'])
# Export to CSV.
# Add the date to the file name to avoid overwriting it each time.
csv_filename = 'name.csv'
with open((src + csv_filename), "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(data)`
这样,不幸的是,如果不包含密钥,代码将完全跳过文件,而我希望它只跳过密钥。所以我尝试了这个,而不是:
import os,json
import glob
import csv
# Place your JSON data in a directory named 'data/'
src = "MY_PATH"
data = []
json_pattern = os.path.join(src, '*.json')
# Change the glob if you want to only look through files with specific names
files = glob.glob(json_pattern, recursive=True)
# Loop through files
col_name = ['name1','name2','name4']
for single_file in files:
with open(single_file, 'r') as f:
json_file = json.load(f)
for key in col_name:
try:
data.append([json_file[key]])
except KeyError:
continue
# Add headers
data.insert(0, ['title_1', 'title_2', 'title_3'])
# Export to CSV.
# Add the date to the file name to avoid overwriting it each time.
csv_filename = 'name.csv'
with open((src + csv_filename), "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(data)
但在这种情况下,每个值都是 csv 中的新行,而我希望每个 json 中的值在一行中。
我不是专家,我真的不知道如何将这两者结合起来。有人可以帮我吗?谢谢!
解决方案
如果我了解您要正确执行的操作,为什么不直接执行
# Loop through files
for single_file in files:
with open(single_file, 'r') as f:
json_file = json.load(f)
data.append([
json_file.get('name1', ''),
json_file.get('name2', ''),
json_file.get('name3', ''),
json_file.get('name4', '')
])
通过使用.get()
,您可以指定默认值,以防找不到键。
推荐阅读
- java - 在不知道 Firebase 实时数据库中的键值的情况下检索子值
- javascript - 获得行动结果的最佳方式是什么?
- c# - 如何使用 EF6 为 Web API 创建域模型的可选日志记录属性?
- twitter - 基本 Twitter 数据挖掘导致问题
- activemq - 使用 .Net 的套接字连接 ActiveMQ
- mysql - VB.NET MySQL 应用程序将无法在客户端 Windows 10 64 位 PC 上连接
- java - maven-javadoc-plugin 最新版本问题
- python - Looping through folder of JSON files to extract the same keyword from each in Python
- python - 替换python中括号之间的所有非字母数字异常
- algorithm - 为什么 Big Theta 在集合 Big O 中,而不是相反的函数?