I am trying to read a JSON file and pass its content to my template like this:
with open('Directory_To_Json', "r") as data:
content = json.load(data)
return render(request, 'Displayer/index.html', {'Content': content})
It works, but I also want to be able to work with the same JSON inside of my javascript. I tried it like this:
var jsonData = JSON.parse("{{Content}}");
But there is an error at the second position, although the JSON itself is valid. (I tried adding the "safe" modifier as well)
I guess it's because I pass it the json.load output, which is formated to work with Python. But how can I pass it the raw json file content?
Thanks in Advance
json.load() returns a dictionary. You can convert a dictionary to a JSON string using json.dumps()
Try this:
with open('Directory_To_Json', "r") as data:
myjson = json.load(data)
content = json.dumps(myjson)
return render(request, 'Displayer/index.html', {'Content': content})
Related
I am rendering the json response data through apiview in django restframework, to html template list.html where i want to retrieve this data in a javascript code.
However everytime it gives "missing ) after argument list error" even though they are not actually present in the data received (as seen in inspect tools of chrome)
Getting the error on
var list =JSON.parse("{{data|safe}}")
The code apiview from views.py which is rendering the data is :
#api_view(['GET','POST'])
def memeList(request):
if request.method=='GET':
meme = Meme.objects.all().order_by('-meme_id')[:100]
serializer = MemeSerializer(meme, many=True)
elif request.method=='POST':
serializer=MemeSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
serJS = JsonResponse(serializer.data,safe=False)
return render(request,'list.html',{'data':serJS.content})
Any solution for this as i have tried all available solutions on the internet still the problem isn't resolved.
The problem lies in the last line in the snippet from your views.py file:
return render(request, 'list.html', {'data': serJS.content})
Here, serJS.content returns a bytestring representing the content. To parse it as JSON, you need to convert it to string, render in the html body and then it will be parsed as JSON correctly. Use this instead:
return render(request, 'list.html', {'data': serJS.content.decode()})
You cannot do this:
var list = JSON.parse("{{data|safe}}")
{{ data|safe }} will render Python objects that cannot be (reliably) parsed as JSON.
What you likely want is to use the json_script template filter. Follow the steps in the docs to get your data as JSON in JavaScript.
I want to export a JSON string in python into a JS variable.
<script type="text/javascript">
var data = JSON.parse('{{ dataJSON }}');
console.log(data)
</script>
If I print the content of dataJSON I get: [{"offset":0,"total":1,"units":[{"village_id":37,"village_name":"Glim
But in the JS I get this: JSON.parse('[{"offset":0,"total":1,"units":[{"village_id":37
I use jinja2 template engine: http://jinja.pocoo.org/docs/dev/templates/#if
How can I fix that?
You need to mark the data as safe:
var data = {{ dataJSON|safe }};
This prevents it from being HTML-escaped. There is no need to use JSON.parse() this way; JSON is a valid JavaScript subset (at least insofar that the Python json module produces a valid subset).
Take into account that this doesn't make it JavaScript safe. You may want to adjust your JSON serialisation. If you are using Flask, a tojson filter is provided that ensures you get JavaScript-safe valid JSON:
var data = {{ data|tojson|safe }};
If you are not using Flask, post-process the JSON:
dataJSON = (json.dumps(data)
.replace(u'<', u'\\u003c')
.replace(u'>', u'\\u003e')
.replace(u'&', u'\\u0026')
.replace(u"'", u'\\u0027'))
This is Python code to produce a dataJSON value that can be safely used in HTML (including attribute values) and in JavaScript. Credit here goes to the Flask json.htmlsafe_dumps() function.
When I try to print my object it gives me no response.
var steaminv = JSON.parse("http://steamcommunity.com/id/pootel/inventory/json/730/2.json");
document.write(steaminv);
You should request the file first and then parse the content of the file.
JSON.parse requires a json object encoded as string. It does not request the file for you.
If you are using node, you can use request module. If you are using javascript on browser, you can use jQuery and do an ajax call to get the content of the file.
Please take a look at this question: How do I receive a JSON file using AJAX and parse it using javascript?
Just to give you an idea what JSON.parse does:
var str = '{"name":"Amir","age":25}';
var obj = JSON.parse(str);
console.log(obj.name);
console.log(obj.age);
I have a very simple view that receives an ajax request containing a javascript object. The jquery request looks like this:
$.get(URL, {'kwargs': {test: 1}}, function(data){//whatever})
The problem is, request.GET now contains a rather strange key and looks like this:
{'kwargs[test]': [1]}
How can I successfully decode this? As a side note, it is impossible to know the key (test) beforehand
The expected format obtained is a python dict that looks like the one in the request.
I've tried:
request.GET.get('kwargs', None)
And I'd expect this as a result:
{'test': 1}
However, I get None, as the real key is 'kwargs[test]'
EDIT
I know I could use some kind of regex to accomplish this, but it feels as 'reinventing the wheel', as this use case is not that rare
I would recommend using JSON when communicating back and forth between the server and client for this type of situation. JSON is meant to handle these types of nested structures in a uniform manner.
Take a look at using the jQuery $.getJSON functionality,
http://api.jquery.com/jquery.getjson/
The following is an example of how this structure would look...
Javscript
var request_data = {kwargs: {test: 1}};
$.getJSON(URL, {data: JSON.stringify(request_data)}, function(data){//whatever})
Django
import json
def your_view(request):
my_json = json.loads(request.GET['data'])
Doing this will allow you to parse the request which contains JSON data into a variable of your choice (my_json). Once you assign your variable with the results of json.loads(), you will now have a python object containing the parsed requested JSON data and you will be able to manipulate your object accordingly.
>>> my_json['kwargs']
{u'test': 1}
I want to export a JSON string in python into a JS variable.
<script type="text/javascript">
var data = JSON.parse('{{ dataJSON }}');
console.log(data)
</script>
If I print the content of dataJSON I get: [{"offset":0,"total":1,"units":[{"village_id":37,"village_name":"Glim
But in the JS I get this: JSON.parse('[{"offset":0,"total":1,"units":[{"village_id":37
I use jinja2 template engine: http://jinja.pocoo.org/docs/dev/templates/#if
How can I fix that?
You need to mark the data as safe:
var data = {{ dataJSON|safe }};
This prevents it from being HTML-escaped. There is no need to use JSON.parse() this way; JSON is a valid JavaScript subset (at least insofar that the Python json module produces a valid subset).
Take into account that this doesn't make it JavaScript safe. You may want to adjust your JSON serialisation. If you are using Flask, a tojson filter is provided that ensures you get JavaScript-safe valid JSON:
var data = {{ data|tojson|safe }};
If you are not using Flask, post-process the JSON:
dataJSON = (json.dumps(data)
.replace(u'<', u'\\u003c')
.replace(u'>', u'\\u003e')
.replace(u'&', u'\\u0026')
.replace(u"'", u'\\u0027'))
This is Python code to produce a dataJSON value that can be safely used in HTML (including attribute values) and in JavaScript. Credit here goes to the Flask json.htmlsafe_dumps() function.