0

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)
Joey
  • 330
  • 2
  • 9

1 Answers1

2

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
niekas
  • 8,187
  • 7
  • 40
  • 58
  • Thanks this works great!!! :) So now in my template I called {{ stocks }} Am I going to have to use django filters to filter that data? I really only want (last: 4204.0) that part but using cut is no problem for me :) This works for me was just gonna see if there was a more efficient way `{{ stocks|cut:"[{u'target': u'stocks.shared (last: "|slice:":4" }}` – Joey Jan 11 '14 at 05:49
  • I suggest to parse the value in view. You could do it by ``stocks[0]['target'].split()[2].strip(')')``. – niekas Jan 11 '14 at 10:15