我如何使用Json作为Django视图上下文

时间:2016-05-17 09:19:58

标签: python json django

我有一个字符串:

daily_program = "{"Training Set":["abc","dxf","gfh"],"Nutrition Set":["acd","dbd","cdf"]}"

我想将它用作上下文字典并将其传递给Django中的模板。如:

def program(request): 
    context = json.loads(daily_program)
    return  render_to_response('program.html',context,RequestContext(request))

它的表现就像python Dict。当我打印出结果时。但我不能将它用作模板中的上下文,例如:

<div>{{Training}}</div>

有没有办法将json对象用作上下文字典?

1 个答案:

答案 0 :(得分:1)

dialy_program应如下所示,使用单引号''来避免构建字符串时出现语法错误:

daily_program = '{"Training":["abc","dxf","gfh"],"Nutrition":["acd","dbd","cdf"]}'