将JSON数据导入Django View / Template [英] Importing JSON data into Django View/Template

查看:125
本文介绍了将JSON数据导入Django View / Template的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在处理一个项目,并使用石墨图形中的json数据,并尝试将其导入django views.py文件,然后在模板中获取所需的值。导入将发生在远程URL上,而不是从服务器本身直接发送。



这是我的json:

  [{target stocks.shared(last:4204.0),datapoints:[[4379.0,1389225600],[4204.0,1389312000]]}] 

这是我的视图文件看起来像

  def get_context_data(self,** kwargs )
context = super(IndexView,self).get_context_data(** kwargs)
上下文['stocks'] = JSON PULL
返回上下文

我尝试过这个,它没有工作,因为json打开并不意味着外部拉。



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / pre>

解决方案

您可以使用 urllib.urlopen 获取外部JSON数据,像这样:

 从urllib import urlopen 

def get_context_data(self,** kwargs) :
context = super(IndexView,self).get_context_data(** kwargs)
my_stock_url ='http://mystockpage.org/stocks/'
上下文['stocks'] = json.loads(urlopen(my_stock_url).read())
上下文['last_stock'] = stock [0] ['target']。split()[2] .strip(')'
return context


So im working on a project and im using json data from a graphite graph and im trying to import it into the django views.py file and then get the value I want in the template. The import will be happening from a remote URL not from directly on the server itself.

here is my json:

[{"target": "stocks.shared (last: 4204.0)", "datapoints": [[4379.0, 1389225600], [4204.0, 1389312000]]}]

This is what my views file will look like

def get_context_data(self, **kwargs):
    context = super(IndexView, self).get_context_data(**kwargs)
    context['stocks'] = JSON PULL
    return context

I tried this and It did not work mostly because json open is not meant to pull externally.

json_data=open('URL')
context['shared'] = json.load(json_data)

解决方案

You can simply use urllib.urlopen to get external JSON data, like this:

from urllib import urlopen

def get_context_data(self, **kwargs):
    context = super(IndexView, self).get_context_data(**kwargs)
    my_stock_url = 'http://mystockpage.org/stocks/'
    context['stocks'] = json.loads(urlopen(my_stock_url).read())
    context['last_stock'] = stocks[0]['target'].split()[2].strip(')')
    return context

这篇关于将JSON数据导入Django View / Template的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆