代码之家  ›  专栏  ›  技术社区  ›  Shankar Panda

如何从python中的csv文件生成json?

  •  3
  • Shankar Panda  · 技术社区  · 6 年前

    我正试图从csv文件构造一个json结构。下面的代码给出了一个错误声明:- attributeError:'tuple'object has no attribute'to_json'. 。我刚接触过python world,希望能在这方面向您寻求帮助。

    csv数据如下:

    我想输出如下

    < PRE> >代码> “variable”:“纬度”, “闽”:“78”, “Q1”:“89”}, “variable”:“经度”, “闽”:“78”, “q1”:“89”, “variable”:“zip”, “闽”:“78”, “Q1”:“89”} ] 进口熊猫 res_data=pd.read_csv(“c\\documents\\abc.csv”,'r') abc=res_data.to_json(orient='records') 打印(ABC) . 我刚接触过python世界,想请你帮忙。

    csv数据如下:

    enter image description here

    我想输出如下

    [
        {"Variable": "Latitude",
        "Min": "78",
        "Q1": "89"} ,
    
        {"Variable": "Longitude",
        "Min": "78",
        "Q1": "89"},
        {"Variable": "Zip",
        "Min": "78",
        "Q1": "89"}
    ]
    
    import pandas    
    res_data = pd.read_csv("C\\Documents\\abc.csv", 'r')
    abc=res_data.to_json(orient='records')
    print(abc)
    
    3 回复  |  直到 6 年前
        1
  •  2
  •   Srce Cde    6 年前
    import json
    import pandas as pd    
    df = pd.read_csv("path_of_csv")
    js = df.to_json(orient="records")
    json.loads(js)
    

    输出:

    [{'variable': 'Latitude', 'min': 26.84505, 'Q1': 31.19725},
     {'variable': 'Longtitude', 'min': -122.315, 'Q1': -116.558},
     {'variable': 'Zip', 'min': 20910.0, 'Q1': 32788.5}]
    
        2
  •  0
  •   elken    6 年前

    类似的东西

    import csv
    import json
    
    csvfile = open('file.csv', 'r')
    jsonfile = open('file.json', 'w')
    
    fieldnames = ("variable", "min", "Q1")
    reader = csv.DictReader( csvfile, fieldnames)
    for row in reader:
        json.dump(row, jsonfile)
        jsonfile.write('\n')
    
        3
  •  0
  •   Harsha Biyani Amit    6 年前

    您可以尝试简单地使用 csv 模块。

    import csv
    import json
    
    output_dict = []
    with open('abc.csv') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            output_dict.append(row)
    
    print json.dumps(output_dict)
    

    输出dict将包含include all rows的dict列表。 json.dumps 将转换python dict json .

    输出将是:

    [{'variable': 'Latitude', 'min': 26.84505, 'Q1': 31.19725},
     {'variable': 'Longtitude', 'min': -122.315, 'Q1': -116.558},
     {'variable': 'Zip', 'min': 20910.0, 'Q1': 32788.5}]
    

    有关csv.dictReader的详细信息: enter link description here