简体   繁体   中英

Remove '[ from JSON when writing to file in Python

I try to write a JSON to a file to use in another program. I have a dataframe which I make into a JSON like this:

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

The output is this

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.

if u want to load json in other program you can use:

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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