【问题标题】:Converting JSON to CSV with missing fieldnames将 JSON 转换为缺少字段名的 CSV
【发布时间】:2020-01-18 14:27:45
【问题描述】:

我很难将 JSON 转换为 csv,因为某些记录上的名称没有显示出来。例如:

[{device: 1,
  name: 'John',
  age: 25,
  city: 'Denver'
 },
 {device: 2,
  name: 'Jake',
  age: 24,
  city: 'New York'
 },
 {device: 3,
  name: 'Phil',
  age: 23}]

这变得更加困难,因为它有几千行,有时这个城市是已知的,有时它不是。

我想把这些放在一个 csv 中,然后把 Phil 的城市留空。

【问题讨论】:

  • 您是否尝试过使用默认架构...这样您就可以轻松找到空值。

标签: json python-3.x csv jsonconvert


【解决方案1】:

你可以用这个:

import json
import csv
js = """[{"device": 1,
  "name": "John",
  "age": 25,
  "city": "Denver"
 },
 {"device": 2,
  "name": "Jake",
  "age": 24,
  "city": "New York"
 },
 {"device": 3,
  "name": "Phil",
  "age": 23}]
  """
js = json.loads(js)

with open( 'result.csv', 'w' ) as csv_file:
    writer = csv.writer( csv_file )
    columns =  list({column for row in js for column in row.keys()})
    writer.writerow( columns )
    for row in js:
        writer.writerow([None if column not in row else row[column] for column in columns])

这甚至适用于不同的列名和更多的列!

【讨论】:

    【解决方案2】:

    在 json to csv 模块中可能有一种内置方法可以做到这一点,但您可以遍历所有 dicts 并添加缺少的键:

    my_list = [{'device':1,
      'name':'John',
      'age':25,
      'city': 'Denver' },
     {'device':2,
      'name':'Jake',
      'age':24,
      'city': 'New York'
     },
     {'device':3,
      'name':'Phil',
      'age':23}]
    
    keys_and_default = {
      'device': -1, 
      'name': 'N/A', 
      'age': -1,
      'city': 'N/A'
    }
    for dic in my_list:
        for key, val in keys_and_default.items():
            if key not in dic:
                dic[key] = val
    print(my_list)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-17
      • 2019-06-20
      • 1970-01-01
      • 2021-01-09
      • 1970-01-01
      相关资源
      最近更新 更多