I am coding a word search game in django, and need to check whether the entered word is in a dictionary. I am currently converting a python dictionary using json.dump, passing it as context to the html page, then passing the json object to a javascript file using a div and the data-words attribute. Finally I parse it in a js function.
Below is a test using one word, and the error I get. I have tried a lot.
- What is sent from py file
- What is show on elements tab on webpage
- js function
{"aardvark": "n. mammal with a tubular snout and a long tongue, feeding on termites. [afrikaans]\n"}
<div id="wordDefinitions" data-words="{" aardvark":="" "n.="" mammal="" with="" a="" tubular="" snout="" and="" long="" tongue,="" feeding="" on="" termites.="" [afrikaans]\n"}"=""></div>
function submit_word() {
var word_dic = JSON.parse(document.getElementById('wordDefinitions').getAttribute('data-words'));
}
Error: Uncaught SyntaxError: Expected property name or ‘}’ in JSON at position 1 (line 1 column 2)
at JSON.parse ()
The error occurs on the parse line and suggests there is something mis-formatted within the JSON but I am too inexperienced to know what. I plan to pass the entire dictionary outside of the function later on, but need this working first.
>Solution :
You need to change " to ‘ in the data-words argument so there won’t be syntax errors.
Try changing this line:
<div id="wordDefinitions" data-words="{" aardvark":="" "n.="" mammal="" with="" a="" tubular="" snout="" and="" long="" tongue,="" feeding="" on="" termites.="" [afrikaans]\n"}"=""></div>
to:
<div id="wordDefinitions" data-words='{"aardvark": "n. mammal with a tubular snout and a long tongue, feeding on termites. [afrikaans]\n"}'></div>