0

I'm sending the below string to a django template.

<script>
var data = '[{"a": 0}, {"b": 1}]'
</script>
  1. How do I get keys as ["a", "b"] using javascript
  2. Also I need a javascript function to retrieve a value for a given key.
1
  • i'm a javascript newbie. sorry about this simple question. Commented Aug 11, 2012 at 14:14

4 Answers 4

1

Just parse it as JSON:

var obj = JSON.parse(data);
obj[0].a // access to a
obj[1].b // access to b
Sign up to request clarification or add additional context in comments.

Comments

1

You need to convert the python object into a format that javascript can understand, i.e json. To do so, use simplejson in your view:

from django.utils import simplejson
from django.shortcuts import render

def some_view(request):
    ...
    python_data = [
        { 'a' : 'foo', 'b' : 'bar' },
        ...
    ]
    json_data = simplejson.dumps(python_data)
    render(request, "some_template.html", { 'data' : json_data })

and in your template:

<script>
var data = {{ data|safe }}
</script>

(Simplejson is fine for converting normal python objects. If you want to convert a QuerySet though, you need to use Django's serialisers)

Comments

0

Why don't you return JSON?

from django.utils import simplejson

def function(request):
    if not request.is_ajax():
        raise Http404
    data = list(
        dict(
            a=0,
            b=1
        )
    )
    return HttpResponse(simplejson.dumps(data), mimetype='application/json')

javascript (using jquery in this example)

function getData(){
    $.ajax({
        type: "GET",
        url: "/your/url/to/function/",
        success: function(data){
            return data;
        }
    });
}
var data = getData();

Comments

0
  1. How do I get keys as ["a", "b"] using javascript

    var arrMain = [{"a": 2}, {"b": 3}],
        arrKey = []; 
    
    for (key in arrMain) { 
        if (arrMain.hasOwnProperty(key)) {
            arrKey.push(Object.keys(arrMain[key])[0]); 
        }
    } 
    
    console.log(JSON.stringify(arrKey)​); // returns ["a","b"]
    
  2. Also I need a javascript function to retrieve a value for a given key.

    function returnValueByKey(arrMain, arrKey, lookupKey) {
        for (key in arrKey) {
            if (arrKey.hasOwnProperty(key) && arrKey[key] === lookupKey) {
               return arrMain[key][arrKey[key]]; 
            }
        }
    }
    
    console.log(returnValueByKey(arrMain, arrKey, 'a')); // returns 2
    

Comments

Your Answer

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