Reputation: 1334
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?
Upvotes: 21
Views: 16227
Reputation: 2680
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)))
Upvotes: 8
Reputation: 294258
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?
Upvotes: -1
Reputation: 52246
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"]]'
Upvotes: 22