如何使用django中的html解析来自context_data的json文件 [英] How to parse a json file from context_data with html in django
问题描述
我有一个这样的JSON文件
I have a JSON file that looks like this
{
"values": {
"a": 1,
"b": 2,
"c": 3,
"d": 4
},
"sales": [
{ "a": 0, "b": 0, "c": 0, "d": 0, "e": "karl" },
{ "a": 0, "b": 0, "c": 0, "d": 0, "e": "karl" },
{ "a": 4, "b": 10, "c": 20, "d": 30, "e": "karl" },
{ "a": 0, "b": 0, "c": 0, "d": 0, "e": "karl" }
]
}
而且我通过 get_context_data
import json
class MyCreateView(CreateView):
def get_context_data(self, **kwargs):
context = super(MyCreateView, self).get_context_data(**kwargs)
with open('/path/to/my/JSON/file/my_json.cfg', 'r') as f:
myfile = json.load(f)
context['my_json'] = my_data
当我做 print myfile [sales] [0] [a]
我得到 0
,当我把 {{my_json}}
加入 index.html
然后我得到整个数组。
which works, when I do print myfile["sales"][0]["a"]
I get 0
and when I put {{my_json}}
into the index.html
then I get the whole array.
所以现在我的问题是如何最好地阅读价值。我必须为每个值创建上下文变量,还是可以读取我的html中的json数组?
So now my question is how to read the values best. Do I have to create context variables for each of the values or is it possible to read the json array in my html?
我尝试过 {{my_json [sales] [0] [a]}}
't work
I tried {{my_json["sales"][0]["a"]}}
but didn't work
推荐答案
如果你想获得 myfile [sales] [0] [您可以使用模板中的]
:
{{my_json.sales.0.a}}
a] 可以这样做:
or if you want to get myfile["values"]["a"]
this can be done like:
{{my_json.values.a}}
这篇关于如何使用django中的html解析来自context_data的json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!