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())
6
  • "Something like"? This is neither valid JSON nor Python... Commented Sep 28, 2012 at 6:29
  • Have you looked at stackoverflow.com/questions/3345076/… Commented Sep 28, 2012 at 6: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() Commented Sep 28, 2012 at 6:30
  • @monkut I edited my post. I think it is because I had the json.loads prior to the return? Commented Sep 28, 2012 at 6:49
  • json.loads() loads the given json data to python objects, which you can access. What is your question here? Commented Sep 28, 2012 at 6:53

3 Answers 3

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)}
    })
Sign up to request clarification or add additional context in comments.

1 Comment

This is the same what I have been using.
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

2 Comments

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?
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.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.