Advertisement
Guest User

Untitled

a guest
Mar 15th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. <script>
  2. var data = '[{"a": 0}, {"b": 1}]'
  3. </script>
  4.  
  5. var obj = JSON.parse(data);
  6. obj[0].a // access to a
  7. obj[1].b // access to b
  8.  
  9. from django.utils import simplejson
  10. from django.shortcuts import render
  11.  
  12. def some_view(request):
  13. ...
  14. python_data = [
  15. { 'a' : 'foo', 'b' : 'bar' },
  16. ...
  17. ]
  18. json_data = simplejson.dumps(python_data)
  19. render(request, "some_template.html", { 'data' : json_data })
  20.  
  21. <script>
  22. var data = {{ data|safe }}
  23. </script>
  24.  
  25. from django.utils import simplejson
  26.  
  27. def function(request):
  28. if not request.is_ajax():
  29. raise Http404
  30. data = list(
  31. dict(
  32. a=0,
  33. b=1
  34. )
  35. )
  36. return HttpResponse(simplejson.dumps(data), mimetype='application/json')
  37.  
  38. function getData(){
  39. $.ajax({
  40. type: "GET",
  41. url: "/your/url/to/function/",
  42. success: function(data){
  43. return data;
  44. }
  45. });
  46. }
  47. var data = getData();
  48.  
  49. var arrMain = [{"a": 2}, {"b": 3}],
  50. arrKey = [];
  51.  
  52. for (key in arrMain) {
  53. if (arrMain.hasOwnProperty(key)) {
  54. arrKey.push(Object.keys(arrMain[key])[0]);
  55. }
  56. }
  57.  
  58. console.log(JSON.stringify(arrKey)​); // returns ["a","b"]
  59.  
  60. function returnValueByKey(arrMain, arrKey, lookupKey) {
  61. for (key in arrKey) {
  62. if (arrKey.hasOwnProperty(key) && arrKey[key] === lookupKey) {
  63. return arrMain[key][arrKey[key]];
  64. }
  65. }
  66. }
  67.  
  68. console.log(returnValueByKey(arrMain, arrKey, 'a')); // returns 2
  69.  
  70. var data = JSON.parse(data);
  71.  
  72.  
  73. var keys = data.reduce(function(arr, obj) {
  74. return arr.concat(Object.keys(obj));
  75. }, []);
  76.  
  77. var value = data[1][keys[1]];
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement