简体   繁体   English

在 Python 中写入文件时,从 JSON 中删除 '[

[英]Remove '[ from JSON when writing to file in Python

I try to write a JSON to a file to use in another program.我尝试将 JSON 写入文件以在另一个程序中使用。 I have a dataframe which I make into a JSON like this:我有一个 dataframe ,我将其制成 JSON ,如下所示:

jsontest = df_qnapairs.to_json(orient = 'records', force_ascii = False)

The output is this output是这里

Out[9]: '[{"id":1,"answer":"Status på Anleggsoverenskomsten er Oppgjør vedtatt","source":"Automatic","questions":["Hva er status på Anleggsoverenskomsten","Hvordan går det med Anleggsoverenskomsten","Når skjer Anleggsoverenskomsten","Status på Anleggsoverenskomsten","Fortell meg når Anleggsoverenskomsten skjer"],"metadata":[]},{"id":2,"answer":"Status på Kraftlinjefirmaer er Ikke oppgitt","source":"Automatic","questions":["Hva er status på Kraftlinjefirmaer","Hvordan går det med Kraftlinjefirmaer","Når skjer Kraftlinjefirmaer","Status på Kraftlinjefirmaer","Fortell meg når Kraftlinjefirmaer skjer"],"metadata":[]}]'

The problem is that the input program runs an error because of the preceding "'[" and trailing "']".问题是输入程序由于前面的“'[”和尾随的“']”而运行错误。 How can I remove these when writing to the file?写入文件时如何删除这些?

if u remove "[" and "]" from it, you change its type from json to dict and in the other program you must be work with dict, i recommend to read and write on file in json format.如果您从中删除“[”和“]”,则将其类型从 json 更改为 dict,在其他程序中您必须使用 dict,我建议以 json 格式读写文件。

if u want to load json in other program you can use:如果您想在其他程序中加载 json,您可以使用:

import json    
json_var = json.loads(var)

if u force to do it, u can change it to string and remove "[" and "]":如果您强制这样做,您可以将其更改为字符串并删除“[”和“]”:

var = str(jsontest)[1:len(str(jsontest))-1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM