【问题标题】:CSV to JSON blocks in PythonPython中的CSV到JSON块
【发布时间】:2019-03-11 04:51:39
【问题描述】:

我有以下 csv 文件。

Occurrences,post_title,ID, System
1, Test 7, 34, Abc
2, Test 9, 55, Xyz
5, Test 11, 87, Pqy
7, Test 3, 71, Cde

问:我想遍历一个循环并将每一行作为 JSON 块发送到 API。例如,我想发送的第一次迭代如下。 {"occurrences": "1", "post_title": "Test 7", "ID" : "34", "System" : "Abc"}

第二次迭代我想发送以下内容。 {"occurrences": "2", "post_title": "Test 9", "ID" : "55", "System" : "Xyz"}

等等……

能否请您使用 Python 提供实现此目的的最佳方法?

【问题讨论】:

    标签: json python-3.x csv


    【解决方案1】:

    这可能会对你有所帮助.. csv.DictReader 会给你一个有序的字典 :)

    import csv
    import json
    input_file = csv.DictReader(open("testing_sid.csv"))
    for row in input_file:
        out = json.dumps(row)
        print(out)
    

    输出:-

    {"Occurrences": "1", "post_title": " Test 7", "ID": " 34", "System": " Abc"}
    {"Occurrences": "2", "post_title": " Test 9", "ID": " 55", "System": " Xyz"}
    {"Occurrences": "5", "post_title": " Test 11", "ID": " 87", "System": " Pqy"}
    {"Occurrences": "7", "post_title": " Test 3", "ID": " 71", "System": " Cde"}
    

    【讨论】:

    【解决方案2】:

    我认为这可能会解决您的问题

    import pandas as pd
    import json
    def get_json(csv_path):
        tabel = pd.read_csv(csv_path)
        row_list = tabel.to_dict('records')
        result = json.dumps(row_list)
        return result
    

    【讨论】:

    • 运行前别忘了安装pandas
    【解决方案3】:

    我会使用愉快地集成了 CSV 和 JSON 支持的 pandas:

    import pandas as pd
    df = pd.read_csv("your_file.csv")
    result = df.apply(lambda x: x.to_json(), axis=1).tolist()
    #['{"Occurrences":1,"post_title":" Test 7","ID" ... "System":" Cde"}']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-09
      • 2017-07-29
      • 1970-01-01
      • 1970-01-01
      • 2017-11-11
      • 2017-08-17
      相关资源
      最近更新 更多