简体   繁体   中英

Forward slash in json file from pandas dataframe

I'm a complete newbie to json, any help is appreciated. I'm trying to convert a dataframe to a json file.

import pandas as pd

df = pd.DataFrame({ 'A' : [1., 2.5],
                    'B' : ['img/blue.png', 'img/red.png']})
print df

Output is

    A             B
0  1.0  img/blue.png
1  2.5   img/red.png

I would like to make a json file that looks like this:

'[1.0,"img/blue.png"],[2.5,"img/red.png"]'

However, when I use the following

out = df.to_json(orient='values')[1:-1]
print out

I get this instead

'[1.0,"img\\/blue.png"],[2.5,"img\\/red.png"]'

How can I get the forward slash to print correctly in the json file?

pandas uses the ujson library under the hood to convert to json, and it seems that it escapes slashes - see issue here .

As a workaround, you could use the python standard library json module to dump the data - it won't be as performant, but won't escape the slashes.

import json

json.dumps(df.values.tolist())
Out[248]: '[[1.0, "img/blue.png"], [2.5, "img/red.png"]]'

I'm not certain but I believe you want those. I think the forward slash will break your json and needs to be escaped. Have you verified that the added back slashes are an issue?

in the part where you are converting the pandas dataframe to json, if you will use loads , it will escape the \\ forward slashes

out = df.to_json(orient='values')[1:-1]
print out

try

import json
print json.dumps(json.loads(out))

for python 3:

import json
print(json.dumps(json.loads(out)))

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