Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert pandas dataframe to json object - pandas

I'm using df.to_json() to convert dataframe to json. But it gives me a json string and not an object. How can I get json object.

Also, when I'm appending this data to an array, it adds single quote before and after the json and it ruins the json structure. How can I export to json object and append properly.

Code used:

a=[]
     array.append(df1.to_json(orient='records', lines=True)) 
     array.append(df2.to_json(orient='records', lines=True)) 

Result:

['{"test:"w","param":1}','{"test:"w2","param":2}]']

Required Result:

[{"test":"w","param":1},{"test":"w2","param":2}]
like image 862
jason Avatar asked May 17 '18 06:05

jason


People also ask

How do I save a 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.

How do I use JSON in Pandas?

You can convert JSON to Pandas DataFrame by simply using read_json() . Just pass JSON string to the function. It takes multiple parameters, for our case I am using orient that specifies the format of JSON string. This function is also used to read JSON files into pandas DataFrame.

How do I convert a Pandas DataFrame to a dictionary?

To convert pandas DataFrame to Dictionary object, use to_dict() method, this takes orient as dict by default which returns the DataFrame in format {column -> {index -> value}} . When no orient is specified, to_dict() returns in this format.

Is Pandas good for JSON?

This API from Pandas helps to read JSON data and works great for already flattened data like we have in our Example 1. You can download the JSON from here.


2 Answers

I believe need create dict and then convert to json:

import json
d = df1.to_dict(orient='records')
j = json.dumps(d)

Or if possible:

j = df1.to_json(orient='records')
like image 166
jezrael Avatar answered Oct 13 '22 08:10

jezrael


Here's what worked for me:

import pandas as pd
import json

df = pd.DataFrame([{"test":"w","param":1},{"test":"w2","param":2}])
print(df)
    test  param
0     w      1
1    w2      2

So now we convert to a json string:

d = df.to_json(orient='records')
print(d)
'[{"test":"w","param":1},{"test":"w2","param":2}]'

And now we parse this string to a list of dicts:

data = json.loads(d)
print(data)
[{'test': 'w', 'param': 1}, {'test': 'w2', 'param': 2}]
like image 40
igorkf Avatar answered Oct 13 '22 08:10

igorkf