javascript - Getting JSON data in a js file In Django Framework -


i have json file want read in , stuff using javascript. within django 1.8. end goal use d3 fancy visualization, while django , python power rest of backend.

i having trouble getting data .json file javascript functions. json file 'uk.json'.

here views.py:

# create views here. def index(request):     data = get_data()     # return jsonify(data)     return render(request, 'pages/index.html')#, {'data': json.dumps(data)})  # api view function data def getuk(request):     json_data = open('/static/js/uk.json')     data1 = json.load(json_data)    # deserializes     data2 = json.dumps(json_data)   # json formatted string      json_data.close()     return jsonresponse(data2) 

here corresponding urls.py:

url(r'^$', views.index, name='index'), url(r'^api/getuk', views.getuk, name='getuk'), 

index.html trying fancy display:

{% load staticfiles %} <!doctype html> <meta charset="utf-8"> <style>  /* css goes here. */  </style>  <body>      <script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>     <script src="//d3js.org/topojson.v1.min.js"></script>     <script src="{% static 'js/graph.js' %}"></script> </body> 

and graph.js want use d3 on json data being passed through.

d3.json("api/getuk", function(error, uk){     if(error) return console.error(error);      console.log(uk); }) 

trying data graph.js can use it. know how without framework, i'm trying work together.

jsonresponse() excepts dict, not json string.

try :

def getuk(request):     open('/static/js/uk.json') json_file:         json_data = json_file.read()         obj = json.loads(json_data)     return jsonresponse(obj) 

Comments