【问题标题】:How to compare a json with a CSV file如何比较 json 和 CSV 文件
【发布时间】:2020-03-27 06:03:21
【问题描述】:

我有一个用于一个服务请求的 json 有效负载。处理后,有效载荷(JSON)将存储在 S3 中,通过 Athena,我们可以以 CSV 格式下载这些数据。现在在实际场景中,有100多个字段。我想通过一些自动化脚本而不是手动来验证它们的价值。

假设我的示例负载类似于以下内容:

{
  "BOOK": {
    "serialno": "123",
    "author": "xyz",
    "yearofpublish": "2015",
    "price": "16"
  }, "Author": [
    {
      "isbn": "xxxxx", "title": "first", "publisher": "xyz", "year": "2020"
    }, {
      "isbn": "yyyy", "title": "second", "publisher": "zmy", "year": "2019"
    }
  ]
}

示例 csv 如下所示:

谁能帮我在 Python 上做这件事吗?也许是图书馆或字典?

【问题讨论】:

  • 请查看您的 JSON 示例。无效。
  • 是的。这我只是做了一些类似于实际有效负载的随机示例,其中 jsonObject 和 jsonArray 都在那里。感谢指正

标签: python json csv compare


【解决方案1】:

看起来您只是想扁平化 JSON 结构。遍历“作者”列表是最容易的。由于 CSV 已重命名列,因此您需要某种方式来表示该映射。仅基于示例,这是可行的:

import json
fin=open(some_json_file, 'r')
j=json.load(fin)
result=[]
for author in j['Author']:
    val = {'book_serialno':       j['BOOK']['serialno'],
           'book_author':         j['BOOK']['author'],
           'book_yearofpublish':  j['BOOK']['yearofpublish'],
           'book_price':          j['BOOK']['price'],
           'author_isbn':         author['isbn'], 
           'author_title':        author['title'],
           'author_publisher':    author['publisher'],
           'author_year':         author['year']}
    result.append(val)

这是使用字典来显示数据点到新列名的映射。您也可以使用列表来侥幸逃脱。取决于您以后要如何使用它。要写入 CSV:

import csv
fout=open(some_csv_file, 'w')
writer=csv.writer(fout)
writer.writerow(result[0].keys())
writer.writerows(r.values() for r in result)

这会在第一行写入列名,然后是数据。如果您不想要列名,只需省略 writerow(...) 行。

【讨论】:

  • 感谢您的解决方案。我要试试这个。只需再查询一个。如果我想在比较过程中跳过任何一个或两个字段,我该怎么做?
  • 如果您想省略一个字段,只需将其从 val 中删除即可。
  • 我已经尝试了上面的代码,它在创建结果时丢失了作者对象之一 [{'book_serialno': '123', 'book_author': 'xyz', 'book_yearofpublish': ' 2015','book_price':'16','author_isbn':'yyyy','author_title':'second','author_publisher':'zmy','author_year':'2019'}]
  • 如果 result.append(val) 在同一个缩进中,那么问题就解决了
  • 但是为什么在 .csv 文件中添加了一些额外的空白行,我仍在试图弄清楚。
猜你喜欢
  • 2020-08-27
  • 2018-12-11
  • 2019-03-01
  • 2021-02-16
  • 1970-01-01
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多