I have a Pandas dataframe with a JSON formatted column, on export of the whole DF as JSON, the JSON column will be formatted like a normal string:
foo = pd.DataFrame({'a' : [1,2,3,4], 'b': ['a','b', 'c','d']})
foo['json'] = foo.apply(lambda x: x[['b']].to_json(), axis=1)
OUTPUT:
a b json
0 1 a {"b":"a"}
1 2 b {"b":"b"}
2 3 c {"b":"c"}
3 4 d {"b":"d"}
foo.to_json()
OUTPUT:
{"a":{"0":1,"1":2,"2":3,"3":4},"b":{"0":"a","1":"b","2":"c","3":"d"},"json":{"0":"{\"b\":\"a\"}","1":"{\"b\":\"b\"}","2":"{\"b\":\"c\"}","3":"{\"b\":\"d\"}"}}
How can I export this without the forward slashes?
Easiest solution is to apply to_dict()
, which is the most native pandas method, although I´m not absolutely sure if its the most performant way.
foo.to_json()
OUTPUT:
'{"a":{"0":1,"1":2,"2":3,"3":4},"b":{"0":"a","1":"b","2":"c","3":"d"},"json":{"0":{"b":"a"},"1":{"b":"b"},"2":{"b":"c"},"3":{"b":"d"}}}'