0

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')]}
6
  • I actually think the screenshots help explain the problem a lot better then trying to reconstruct in markdown. I mentioned flask becuase that was the framework I was using and ok i missed one tag. Must of had a rough day to downvote with out giving the poster a chance to modify Commented Dec 11, 2019 at 22:07
  • can you share us a few example fo your dataframe in a csv file ? transferbigfiles.com Commented Dec 11, 2019 at 22:09
  • 2
    you're incorrect in that the screenshots explain the problem better. it makes it significantly more difficult for us to help you if we have to open your code in another window to look at it and don't have the ability to copy/paste into our own shell. screenshots can add additional context but do not take the place of code. Commented Dec 11, 2019 at 22:14
  • added simple example Commented Dec 11, 2019 at 22:16
  • Those backslashes serve a purpose, no? Commented Dec 12, 2019 at 1:46

1 Answer 1

4

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())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.