Pandas 到 JSON 文件格式问题,将 \ 添加到字符串

Pandas to JSON file formatting issue, adding \ to strings

我正在使用 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}]

在将数据转换为文件格式时,是否有我应该 including/excluding 的格式?

您的 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')