【问题标题】:Pandas to JSON file formatting issue, adding \ to stringsPandas 到 JSON 文件格式问题,将 \ 添加到字符串
【发布时间】:2021-04-13 11:43:18
【问题描述】:

我正在使用pandas.DataFrame.to_json 将数据框转换为 JSON 数据。

data = df.to_json(orient="records")
print(data)

这工作正常,打印时的输出与控制台中的预期一致。

[{"n":"f89be390-5706-4ef5-a110-23f1657f4aec:voltage","bt":1610040655,"u":"V","v":237.3},
{"n":"f89be390-5706-4ef5-a110-23f1657f4aec:power","bt":1610040836,"u":"W","v":512.3},
{"n":"f89be390-5706-4ef5-a110-23f1657f4aec:voltage","bt":1610040840,"u":"V","v":238.4}]

将其上传到将其转换为文件格式或将其写入本地文件的外部 API 时会出现问题。输出已将\ 添加到字符串的开头和结尾。

def dataToFile(processedData):
    with open('data.json', 'w') as outfile:
        json.dump(processedData,outfile)

结果显示在下面的剪辑中

[{\"n\":\"f1097ac5-0ee4-48a4-8af5-bf2b58f3268c:power\",\"bt\":1610024746,\"u\":\"W\",\"v\":40.3},
{\"n\":\"f1097ac5-0ee4-48a4-8af5-bf2b58f3268c:voltage\",\"bt\":1610024751,\"u\":\"V\",\"v\":238.5},
{\"n\":\"f1097ac5-0ee4-48a4-8af5-bf2b58f3268c:power\",\"bt\":1610024764,\"u\":\"W\",\"v\":39.7}]

在将数据转换为文件格式时,我应该特别包含/排除任何格式吗?

【问题讨论】:

  • 看起来 processedData 是一个字符串,而不是 JSON 对象。您可以在转储之前打印repr(processedData)。即如果它已经是 JSON 字符串,则不需要转储它。
  • df.to_json() 返回一个字符串,而不是字典,所以你不需要json.dump()

标签: python json pandas string file-format


【解决方案1】:

您的 data 变量是一串 json 数据,而不是实际的字典。你可以做几件事:

  1. 使用DataFrame.to_json()写入文件,to_json()的第一个参数是文件路径:
df.to_json('./data.json', orient='records')
  1. 直接将json字符串写成文本:
def write_text(text: str, path: str):
    with open(path, 'w') as file:
        file.write(text)

data = df.to_json(orient="records")

write_text(data, './data.json')
  1. 如果您想玩弄字典数据:
def write_json(data, path, indent=4):
    with open(path, 'w') as file: 
        json.dump(data, file, indent=indent)

df_data = df.to_dict(orient='records')

# ...some operations here...

write_json(df_data, './data.json')

【讨论】:

  • 是的,这解决了我的问题,我确实使用 ``` json.loads() ``` 使用了轻微的变化来玩字典,因为我并不总是需要文件,谢谢!
猜你喜欢
  • 1970-01-01
  • 2017-03-10
  • 1970-01-01
  • 2012-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 2020-02-16
相关资源
最近更新 更多