【问题标题】:How to write the JSON structured data to a text file in Python?如何将 JSON 结构化数据写入 Python 中的文本文件?
【发布时间】:2019-04-19 12:36:21
【问题描述】:

我正在尝试将我的 JSON 结构化数据写入 JSON 文件。 js 数据框包含这样的 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)

【问题讨论】:

    标签: python json python-3.x python-2.7 pandas


    【解决方案1】:

    我认为您正在对数据进行双重编码 - df.to_json 将数据转换为 JSON 字符串。然后你正在运行json.dump,然后将已经编码的字符串再次编码为 JSON - 这导致将现有 JSON 包装在引号中并用反斜杠转义所有内部引号你最终得到 JSON-within-JSON,这是不必要或不可取的。

    您应该使用这些方法中的一种或其他,但不能同时使用这两种方法。最简单的方法可能是使用df.to_json 准确地序列化数据帧数据,然后将字符串作为文本直接写入文件。

    【讨论】:

    • df = pd.read_csv('C:\\Users\\spanda031\\Downloads\\data_new.csv','w') df.to_csv(js) 我用它来写一个 csv 但结果仍然相同
    • 如何将其写入 CSV 产生相同的结果?这与编码为 JSON 无关。如果js 是 JSON,你为什么要尝试将其写为 CSV?这是没有意义的。只需将其写为纯文本即可。现在似乎有人向您展示了正确的方法,所以希望不再有问题。
    【解决方案2】:
    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}]
    

    【讨论】:

      【解决方案3】:

      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)
      

      【讨论】:

      • 谢谢。和 +1 (谈话这么便宜,为什么不让我给你看代码?)
      猜你喜欢
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-21
      • 1970-01-01
      • 2012-08-31
      相关资源
      最近更新 更多