首页 > 解决方案 > 从 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 中的值在一行中。

我不是专家,我真的不知道如何将这两者结合起来。有人可以帮我吗?谢谢!

标签: pythonjsonexport-to-csv

解决方案


如果我了解您要正确执行的操作,为什么不直接执行

# 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(),您可以指定默认值,以防找不到键。


推荐阅读