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

Python+Django下JSON数据格式化及指定字段(名称、价格)展示问题

解决Django中展示JSON指定字段的问题

看起来你踩了个常见的小坑——用BeautifulSoup处理API返回的JSON数据,但BeautifulSoup是专门解析HTML/XML的工具,完全不适合处理JSON格式。咱们一步步来修正:

第一步:正确解析并筛选JSON数据

先把你item.py里的BeautifulSoup代码删掉,换成JSON解析逻辑。API返回的是纯JSON格式,直接用requests的json()方法就能转换成Python字典,然后提取你需要的字段:

import requests
from django.shortcuts import render

def item_prices(request):
    # 补全完整的API URL(必须带https://这类协议头)
    api_url = 'https://api.eveonline.com/xxxxx'
    response = requests.get(api_url)
    # 把JSON响应转成Python字典
    raw_data = response.json()
    
    # 筛选目标字段:name在type嵌套对象里,averagePrice是直接字段
    filtered_items = []
    for item in raw_data['items']:
        filtered_item = {
            'name': item['type']['name'],
            'average_price': item['averagePrice']
        }
        filtered_items.append(filtered_item)
    
    # 把筛选好的数据传给Django模板
    return render(request, 'item_prices.html', {'items': filtered_items})

第二步:在Django模板中渲染指定字段

创建(或修改)你的模板文件item_prices.html,用Django模板语法循环展示筛选后的内容:

<h2>物品名称与均价</h2>
<div class="price-list">
    {% for item in items %}
        <div class="item-entry">
            <span class="item-name">{{ item.name }}</span>
            <span class="item-price">¥{{ item.average_price }}</span>
        </div>
    {% empty %}
        <p>暂无数据可展示</p>
    {% endfor %}
</div>

关键提醒

  • 你的原始JSON里name是嵌套在type对象里的,必须用item['type']['name']才能拿到正确值,直接写item['name']会报错。
  • 一定要确保API URL是完整的(带协议头),否则requests会无法正常请求。
  • 如果API需要认证或特定请求头,记得在requests.get()里添加对应的参数(比如headers={'Authorization': 'Bearer xxx'})。

这样处理后,网页上就只会显示你需要的名称和平均价格字段啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:41:46