Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 889
edge-case Avatar asked Apr 14 '17 14:04

edge-case


People also ask

How do I pass forward slash in JSON?

JSON escapes the forward slash, so a hash {a: "a/b/c"} is serialized as {"a":"a\/b\/c"} instead of {"a":"a/b/c"} .

Why does my JSON have slashes?

Those backslashes are escape characters. They are escaping the special characters inside of the string associated with JSON response. You have to use JSON.

How do I export Pandas DataFrame to JSON?

To convert the object to a JSON string, then use the Pandas DataFrame. to_json() function. Pandas to_json() is an inbuilt DataFrame function that converts the object to a JSON string. To export pandas DataFrame to a JSON file, then use the to_json() function.


3 Answers

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"]]'
like image 146
chrisb Avatar answered Oct 06 '22 11:10

chrisb


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)))
like image 24
Upasana Mittal Avatar answered Oct 06 '22 11:10

Upasana Mittal


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?

like image 41
piRSquared Avatar answered Oct 06 '22 10:10

piRSquared