0

I have 2 dataframes. I have to send these two dataframes in json format whenever the django API is called.

c = a.to_json(orient='records')
d = b.to_json(orient='records')
return JsonResponse(json.loads(c,d),safe = False)

a and b are dataframes

I'm getting error when I'm executing the above code. How to send the 2 separate dataframes in json format.

Theguy
  • 33
  • 9

1 Answers1

2

You need to put the dataframes into some sort of structure that can then be serialized back to json. One way would be:

c = json.loads(a.to_json(orient='records'))
d = json.loads(b.to_json(orient='records'))
return JsonResponse([c, d], safe = False)

This will avoid having a double-serialized string.

tghw
  • 25,208
  • 13
  • 70
  • 96
  • Thanks. Works perfectly. Is there a way to label each dataframe in the json format so that it is easy to pick dataframe from the json format? – Theguy Dec 17 '20 at 16:36
  • Yes, in that case you would use a dictionary instead of a list. So instead of `[c, d]` you would pass `{'c': c, 'd': d}` into `JsonRsponse`. `'c'` and `'d'` can be whatever you want them to be. – tghw Dec 17 '20 at 16:45
  • 1
    Thanks a lot. Works perfectly – Theguy Dec 17 '20 at 16:52