【问题标题】:Python: How to save a JSON file without brackets?Python:如何保存不带括号的 JSON 文件?
【发布时间】:2020-04-13 19:51:36
【问题描述】:

我正在尝试生成一个 JSON 文件,但是它生成的不是有意的括号。我该如何克服这个问题?

代码

import pandas as pd

df = pd.DataFrame({"A": [10],
                   "B": [20],
                   "C": [30]})

df.to_json('file.json', orient='records')

file.json

[{"A":10,"B":20,"C":30}]

预期输出

 {"A":10,"B":20,"C":30}

【问题讨论】:

    标签: json python-3.x pandas


    【解决方案1】:

    使用选项lines=True。您不会在文件中获得方括号并获得所需的输出。

    df.to_json('file.json', orient='records', lines=True)
    

    【讨论】:

      【解决方案2】:

      如果您在columns 上使用orient,它与您想要的非常接近,但包含索引:

      df.to_json(orient="columns")
      # '{"A":{"0":10},"B":{"0":20},"C":{"0":30}}'
      

      给你{column -> {index -> value}}

      以下是您的 DataFrame 的所有输出:

        split    {"columns":["A","B","C"],"index":[0],"data":[[10,20,30]]}
      records    [{"A":10,"B":20,"C":30}]
        index    {"0":{"A":10,"B":20,"C":30}}
      columns    {"A":{"0":10},"B":{"0":20},"C":{"0":30}}
       values    [[10,20,30]]
        table    {"schema":{"fields":[{"name":"index","type":"integer"},{"name":"A","type":"integer"},{"name":"B","type":"integer"},{"name":"C","type":"integer"}],"primaryKey":["index"],"pandas_version":"0.20.0"},"data":[{"index":0,"A":10,"B":20,"C":30}]}
      

      使用to_dict 定位为list

      repr(df.to_dict(orient="list"))
      # "{'A': [10], 'B': [20], 'C': [30]}"
      

      这是reprs 的其余部分to_dict

         dict    {'A': {0: 10}, 'B': {0: 20}, 'C': {0: 30}}
         list    {'A': [10], 'B': [20], 'C': [30]}
       series    {'A': 0    10
      Name: A, dtype: int64, 'B': 0    20
      Name: B, dtype: int64, 'C': 0    30
      Name: C, dtype: int64}
        split    {'index': [0], 'columns': ['A', 'B', 'C'], 'data': [[10, 20, 30]]}
      records    [{'A': 10, 'B': 20, 'C': 30}]
        index    {0: {'A': 10, 'B': 20, 'C': 30}}
      

      【讨论】:

      • 可以删除索引吗?
      • 我能得到的最接近的是使用to_dict(请参阅更新的答案)。
      猜你喜欢
      • 2022-11-22
      • 2019-11-08
      • 2021-11-24
      • 2017-12-01
      • 2011-03-07
      • 1970-01-01
      • 2016-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多