Rach Odwyer
Rach Odwyer

Reputation: 184

Creating JSON from multiple dataframes python

My code works perfect fine for 1 dataframe using the to_json

enter image description here

However now i would like to have a 2nd dataframe in this result.

So I thought creating a dictionary would be the answer.

However it produces the result below which is not practical.

Any help please

I was hoping to produce something a lot prettier without all the "\"

enter image description here

A simple good example

import pandas as pd
data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data)
df.to_json(orient='records')

A simple bad example

import pandas as pd
data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data)
{"result_1": df.to_json(orient='records')}

I also tried

jsonify({"result_1": df.to_json(orient='records')})

and

{"result_1": [df.to_json(orient='records')]}

Upvotes: 0

Views: 2301

Answers (1)

Giuseppe Saraceno
Giuseppe Saraceno

Reputation: 101

Hi I think that you are on the right way. My advice is to use also json.loads to decode json and create a list of dictionary.

As you said before we can create a pandas dataframe and then use df.to_json to convert itself. Then use json.loads to json format data and create a dictionary to insert into a list e.g. :

data = {}
jsdf = df.to_json(orient = "records")
data["result"] = json.loads(jsdf)

Adding elements to dictionary as below you will find a situation like this:

{"result1": [{...}], "result2": [{...}]}

PS: If you want to generate random values for different dataframe you can use faker library from python. e.g.:

from faker import Faker

faker = Faker()

for n in range(5):
    df.append(list(faker.profile().values()))
df = pd.DataFrame(df, columns=faker.profile().keys())

Upvotes: 4

Related Questions