【问题标题】:How to return multiple dataframes as JsonResponse in Django?如何在 Django 中将多个数据帧作为 JsonResponse 返回?
【发布时间】:2020-12-17 15:50:20
【问题描述】:

我有 2 个数据框。每当调用 django API 时,我都必须以 json 格式发送这两个数据帧。

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

a 和 b 是数据帧

执行上述代码时出现错误。如何以 json 格式发送 2 个单独的数据帧。

【问题讨论】:

  • 我想你想使用json.dumps

标签: python json django django-rest-framework jsonresponse


【解决方案1】:

您需要将数据帧放入某种结构中,然后再将其序列化回 json。一种方法是:

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

这样可以避免双序列化字符串。

【讨论】:

  • 谢谢。完美运行。有没有办法将每个数据帧标记为 json 格式,以便轻松从 json 格式中选择数据帧?
  • 是的,在这种情况下,您将使用字典而不是列表。因此,您可以将{'c': c, 'd': d} 传递给JsonRsponse,而不是[c, d]'c''d' 可以是你想要的任何东西。
  • 非常感谢。完美运行
猜你喜欢
  • 2017-12-24
  • 2021-03-19
  • 1970-01-01
  • 2017-02-07
  • 2021-03-03
  • 2021-11-26
  • 1970-01-01
  • 2019-11-16
  • 1970-01-01
相关资源
最近更新 更多