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?
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"} .
Those backslashes are escape characters. They are escaping the special characters inside of the string associated with JSON response. You have to use 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.
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"]]'
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)))
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With