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

如何在Python中将JSON结构化数据写入文本文件?

  •  -1
  • Shankar Panda  · 技术社区  · 6 年前

    我正在尝试将JSON结构化数据写入JSON文件。 js dataframe包含如下JSON数据:

    [{"variable":"Latitude","min":26.845043,"Q1":31.1972475},{"variable":"Longitude","min":-122.315002,"Q1":-116.557795},{"variable":"Zip","min":20910.0,"Q1":32788.5}]
    

    但当我将其写入文件时,数据的存储方式不同。你能帮我把结果像存储在数据框(js)中一样存储吗?

    "[{\"variable\":\"Latitude\",\"min\":26.845043,\"Q1\":31.1972475},{\"variable\":\"Longitude\",\"min\":-122.315002,\"Q1\":-116.557795},{\"variable\":\"Zip\",\"min\":20910.0,\"Q1\":32788.5}]"
    

    代码:

    import csv
    import json
    import pandas as pd    
    df = pd.read_csv(r'C:\Users\spanda031\Downloads\DQ_RESUlT.csv')
    js = df.to_json(orient="records")
    print(js)
    
    # Read JSON file
    with open('C:\\Users\\spanda031\\Downloads\\data.json', 'w') as data_file:
        json.dump(js,data_file)
    
    3 回复  |  直到 6 年前
        1
  •  3
  •   Srce Cde    6 年前
    import pandas as pd
    import json
    df = pd.read_csv("temp.csv")
    # it will dump json to file
    df.to_json("filename.json", orient="records")
    

    filename.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}]
    
        2
  •  1
  •   ADyson    6 年前

    我认为你在双重编码你的数据- df.to_json json.dump 然后将已经编码的字符串再次编码为JSON——这会导致将现有JSON包装在引号中,并用反斜杠转义所有内部引号,最终在JSON中使用JSON,这是不必要的,也不可取的。

    您应该使用其中一种方法,但不能同时使用这两种方法。它可能是最容易使用的 df.to_json

        3
  •  1
  •   Mark White    6 年前

    Talk很便宜,为什么不让我给你看看代码呢?

    import csv
    import json
    import pandas as pd    
    df = pd.read_csv(r'C:\Users\spanda031\Downloads\DQ_RESUlT.csv')
    // where magic happends! :)
    js = df.to_dict(orient="records")
    print(js)
    
    # Read JSON file
    with open('C:\\Users\\spanda031\\Downloads\\data.json', 'w') as data_file:
        json.dump(js,data_file)