How to Convert DataFrame to JSON without Backslash in Pandas

In this short tutorial, you'll see the steps to convert DataFrame to JSON without backslash escape in Pandas and Python.

Note: Read also: How to Export DataFrame to JSON with Pandas

Suppose we have the following DataFrame:

Name Age site
0 Alice 25 http://example.com/
1 Bob 30 http://example.com/
2 Charlie 35 http://example.com/

Here is the result of the conversion with to_json() with option orient='records':

df.to_json(orient='records',lines=True)

We get a valid JSON file but with extract backslashes:

{"Name":"Alice","Age":25,"site":"http:\/\/example.com\/"}
{"Name":"Bob","Age":30,"site":"http:\/\/example.com\/"}
{"Name":"Charlie","Age":35,"site":"http:\/\/example.com\/"}

To convert Pandas DataFrame to JSON file without backslash escapes:

formatted_json = df.to_json(orient='records',lines=True).replace('\\/', '/')
print(formatted_json)

This will replace all additional backslash escapes with:

{"Name":"Alice","Age":25,"site":"http://example.com/"}
{"Name":"Bob","Age":30,"site":"http://example.com/"}
{"Name":"Charlie","Age":35,"site":"http://example.com/"}

To store the JSON data as a file without backslash we can do:

print(formatted_json, file=open('data.json', 'w'))

We can get this result without lines=True:

[
{
"Name": "Alice",
"Age": 25,
"site": "http://example.com/"
},
{
"Name": "Bob",
"Age": 30,
"site": "http://example.com/"
},
{
"Name": "Charlie",
"Age": 35,
"site": "http://example.com/"
}
]