[英]How to access attribute elements from a JSON file in Django Template?
我正在解析一个位于远程且不断更新新数据的 JSON 文件。 我不打算写 JSON 文件的整个结构,因为它太多了。 到目前为止,我可以在模板上获取并显示名称和图像,这很简单,但我不知道如何访问具有属性和前导下划线的某些元素。
让我们看看 JSON 文件的一部分:
[{ 'searchResult' : [{'@count': '5',
'item': [{
'itemId': ['352565431707'],
'title': ['Smart Tab ST8200 Quad-core 7" HD Tablet Android 8.1 Oreo 8GB'],
'galleryURL': ['http://thumbs4.flickr.com/m/maf6ZygaFcxqMsVv2DQTh6g/140.jpg'],
'sellingStatus': [{'currentPrice': [{'@currencyId': 'USD', '__value__': '49.0'}],
'itemURL': ['http://rover.somewebsite.com?item=352565431707']}]
'item': [{
'itemId': ['352565431808'],
'title': ['iPhone 11 latest phone '],
'galleryURL': ['http://thumbs4.flickr.com/m/maf6ZygaFcxqMsVv2DQOm6g/140.jpg'],
'sellingStatus': [{'currentPrice': [{'@currencyId': 'USD', '__value__': '1200.0'}],
'itemURL': ['http://rover.somewebsite.com?item=352565431808']}]
这是我在views.py 中的代码的一部分
url = 'http://svcs.somewebsite.com?RESPONSE-DATA-FORMAT=JSON&keyword=something'
r = requests.get(url).json()
search =r['searchResult'][0]['item']
context = { 'items': search }
template='home.html'
return render(request, template, context)
这是我在home.html模板中的代码的一部分
{% for item in items %}
<a href = "{{ item.itemURL.0 }} />
<img src="{{ item.galleryURL.0 }}" alt="{{ item.title.0 }}" />
</a>
<h2>{{ item.title.0 }}</h2>
<h3>{{ item.sellingStatus.0.currentPrice.0.__value__.0 }}</h3>
{% endfor %}
根据我拥有的内容呈现图像和标题,但是当我尝试访问__value__ 时,由于前导下划线,我收到一条错误消息,老实说,我不知道我是否使用这种方法正确访问了属性. 回到我的问题,如何在这种特殊情况下访问属性以及如何转义前导下划线? 非常感谢您提供任何帮助。
朋友,您必须使用在 FOR 循环中声明的相同变量。 您必须使用 item 变量而不是 items。 从技术上讲,该区域不存在项目:
{% for item in items %}
<a href="{{item .viewItemURL.0}}">
<img src="{{ item .galleryURL.0 }}" alt="{{ item .title.0 }}" />
</a>
<p>Names: {{ item .title.0 }}</p>
{% endfor %}
朋友,你的问题解决了吗? 如果没有,一个可能更简单的解决方案是使用 javascript。 尝试以某种方式将标签变量 {{items}} 存储在 javascript 变量中。
for (let item in variableItems){
let currentPrice = variableItems[item].sellingStatus[0].currentPrice[0];
console.log(currentPrice['@currencyId'];
console.log(currentPrice['__value__'];
}
完成此操作后,将值用于您想要的目的。
另一种可能的解决方案是在后端删除 @ 字符和 __ (因为 @ 字符会在模板中产生问题)。 您可以使用替换功能。 str.replace('@', '')
和 str.replace('__' , '')
y en la pantilla html:
{{ item.sellingStatus.0.currentPrice.0.currencyId}}
{{ item.sellingStatus.0.currentPrice.0.value}}
因为我喜欢与世界分享我所知道的,所以这里是我自己问题的答案。 在做了一些研究并摸索了几天之后,我想出了这个解决方案,这对我的情况很有用。
为了访问属性元素和前导下划线,我必须清理视图中的数据并在视图中进行迭代。 我创建了四个变量容器,用于附加该迭代的每个结果。 如果你不这样做,你最终只会得到模板中迭代的最后结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.