0

I'm trying to learn django/python and I'm trying to figure out how to read json data...

I have something like :

{
  region: {
    span: {
       latitude_delta: 0.08762885999999526,
       longitude_delta: 0.044015180000002374
    },
    center: {
       latitude: 37.760948299999995,
       longitude: -122.4174594
    }
  },...
}

I'm trying to read specific data in my html page. Right now this json data is being displayed in the html page.

The source of the this json comes from this:

return HttpResponse(json.dumps(response),mimetype="application/json")

I'm trying to figure out the django/python convention of getting specific data? Am I supposed to do a for each loop? I come from a self taught php background, and I'm trying to teach myself python/django.

Thank you

edit:

I also have this in my view.py before the return HttpResponse

    try:
        conn = urllib2.urlopen(signed_url, None)
        try:
            response = json.loads(conn.read())
        finally:
            conn.close()
    except urllib2.HTTPError, error:
        response = json.loads(error.read())
hellomello
  • 8,219
  • 39
  • 151
  • 297
  • "Something like"? This is neither valid JSON nor Python... – Tim Pietzcker Sep 28 '12 at 06:29
  • Have you looked at http://stackoverflow.com/questions/3345076/django-parse-json-in-my-template-using-javascript – Rohan Sep 28 '12 at 06:29
  • 1
    ? this is a bit confusing... you manage to create the json using json.dumps(response), response should be your data as python objects. json.dumps() turns it into json. The opposite of json.dumps() is json.loads() – monkut Sep 28 '12 at 06:30
  • @monkut I edited my post. I think it is because I had the json.loads prior to the return? – hellomello Sep 28 '12 at 06:49
  • json.loads() loads the given json data to python objects, which you can access. What is your question here? – monkut Sep 28 '12 at 06:53
  • @monkut I'm trying to figure out how to get specific data when doing for loops? Or what is the python convention? Typically when I'm dealing with PHP I would do something like `foreach($datas as $data){echo $data['region'];}` or something. – hellomello Sep 28 '12 at 07:07

3 Answers3

1

This is the easiest way to read json in html (Send by Django)

def sendJson(request):
    if request.method == 'GET':
        context = {"name":"Json Sample Data"}
        return render_to_response('name.html',context)        

Django Template Html Code

<div class="col-md-9 center">
    <span class="top-text">{{name}}</span>
</div>

Now according to your:

 def sendJson(request):
    if request.method == 'GET':
        jsonData = {
          region: {
           span: {
            latitude_delta: 0.08762885999999526,
            longitude_delta: 0.044015180000002374
          },
          center: {
            latitude: 37.760948299999995,
            longitude: -122.4174594
          }
        }
       }
       data = json.dumps(jsonData)
       return HttpResponse(data, content_type="application/json")

you can read this data by using jquery also

another example to create json and read in html

url.py

url(r'^anotherexample/$', 'views.anotherexample', name="anotherexample"),

view.py

 def anotherexample(request):
    if request.method == 'POST':
       _date = strftime("%c")
       response_data = {}
       response_data['status'] = 'taken'
       response_data['issueTakenTime'] = _date
       return HttpResponse(json.dumps(response_data), content_type="application/json")

Html view and jquery

$.ajax({
    url: "/anotherexample/",
    // contentType: "application/json; charset=UTF-8",
    data: { csrfmiddlewaretoken: "{{ csrf_token }}",   // < here 
        status : "taken"
      },
    type: "POST",
    error: function(res) {
      console.log("errr", res)
    },
    success: function(res) {
      console.log("res", res)}
    })
Atul Jain
  • 1,053
  • 11
  • 36
0

It's not clear what you want to loop over, where, or how, but basic loops work like this:

data = {"key1":[1,2], "key":[4,5]}
for key, values in data.iteritems():
    print key, values
monkut
  • 42,176
  • 24
  • 124
  • 155
  • This would go into my views.py under the same `def`? example if all my code is in `def search(request)`, I'm just trying to see if I'm supposed to loop inside the .html file? or loop in the view.py file? I dunno if that makes sense to you? – hellomello Sep 28 '12 at 07:15
  • hmmm... well you can create a loop and parse objects in the view, or loop in the template. I would say generally it's easier to manage data in the view to put it into a clean structure before passing to the template. If you haven't already I suggest you try the python tutorial and then the django tutorial. – monkut Sep 28 '12 at 07:30
0

I was able to figure out the solution through this link: Decode json and Iterate through items in django template

It helped me and hopefully it'll help someone else who has the same problem as me.

Thanks

Community
  • 1
  • 1
hellomello
  • 8,219
  • 39
  • 151
  • 297