Forward slash in json file from pandas dataframe

為{幸葍}努か 提交于 2021-02-18 22:11:26

问题


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?


回答1:


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?




回答2:


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"]]'



回答3:


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)))


来源:https://stackoverflow.com/questions/43413119/forward-slash-in-json-file-from-pandas-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!