Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <script>
- var data = '[{"a": 0}, {"b": 1}]'
- </script>
- var obj = JSON.parse(data);
- obj[0].a // access to a
- obj[1].b // access to b
- 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 })
- <script>
- var data = {{ data|safe }}
- </script>
- 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')
- function getData(){
- $.ajax({
- type: "GET",
- url: "/your/url/to/function/",
- success: function(data){
- return data;
- }
- });
- }
- var data = getData();
- 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"]
- 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
- var data = JSON.parse(data);
- var keys = data.reduce(function(arr, obj) {
- return arr.concat(Object.keys(obj));
- }, []);
- var value = data[1][keys[1]];
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement