Reputation: 1272
I have a JSON file that I want to read in and do some stuff with using javascript. This is all within Django 1.8. The end goal is to use D3 to do some fancy visualization, while Django and Python power the rest of the backend.
I am having trouble getting the data from .json file to the javascript functions. The json file is 'uk.json'.
Here is my views.py:
# Create your views here.
def index(request):
data = get_data()
# return jsonify(data)
return render(request, 'pages/index.html')#, {'data': json.dumps(data)})
# api view function to get the data
def getuk(request):
json_data = open('/static/js/uk.json')
data1 = json.load(json_data) # deserializes it
data2 = json.dumps(json_data) # json formatted string
json_data.close()
return JsonResponse(data2)
Here is my corresponding urls.py:
url(r'^$', views.index, name='index'),
url(r'^api/getuk', views.getuk, name='getuk'),
index.html where I am trying to get all this 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 finally my graph.js where I want to use D3 on the json data being passed through.
d3.json("api/getuk", function(error, uk){
if(error) return console.error(error);
console.log(uk);
})
trying to get the data into graph.js so I can use it. I know how to do this normally without a framework, but I'm trying to get this all to work together.
Upvotes: 1
Views: 2653
Reputation: 1272
The reason was I need to create a temporary var
in html with django template tags with autoescape off.
var temp = {{ data | safe }};
Then the variable temp
is available for play in my .js file
Upvotes: 1
Reputation: 11943
JsonResponse()
excepts a dict, not a json string.
Try :
def getuk(request):
with open('/static/js/uk.json') as json_file:
json_data = json_file.read()
obj = json.loads(json_data)
return JsonResponse(obj)
Upvotes: 0