You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django如何提取CEX API返回对象内嵌数组字段并渲染表格

问题原因

你现在遍历的是接口返回的完整JSON字典,它的顶层只有data一个键,Django模板遍历字典时默认输出键名,所以只会渲染出data。

解决方法

有两种实现方案可选:

方案1(推荐):后端提前提取数据列表

在views.py中处理接口返回值时,直接取出data字段对应的列表再传给模板,减少模板层逻辑:

# 假设接口返回的原始JSON数据存在api_res变量中
price_data = api_res.json()
context = {
    'price_list': price_data['data']
}

模板中直接遍历列表渲染表格即可:

<table>
  <thead>
    <tr>
      <th>交易金额</th>
      <th>标的币种</th>
      <th>计价币种</th>
    </tr>
  </thead>
  <tbody>
    {% for item in price_list %}
    <tr>
      <td>{{ item.amount }}</td>
      <td>{{ item.base }}</td>
      <td>{{ item.currency }}</td>
    </tr>
    {% endfor %}
  </tbody>
</table>

方案2:不改后端代码,模板层直接取值

如果不想修改views的传值逻辑,直接在模板内取price.data遍历即可:

<table>
  <thead>
    <tr>
      <th>amount</th>
      <th>base</th>
      <th>currency</th>
    </tr>
  </thead>
  <tbody>
    {% for item in price.data %}
    <tr>
      <td>{{ item.amount }}</td>
      <td>{{ item.base }}</td>
      <td>{{ item.currency }}</td>
    </tr>
    {% endfor %}
  </tbody>
</table>

注意事项

你贴出的接口返回示例存在语法错误,amount键名后缺少右引号,实际调用接口解析数据时要注意修正,避免JSON解析失败报错。

内容的提问来源于stack exchange,提问作者Jack_T

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 17:27:03