Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to get JavaScript to parse JSON from html file

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.

  1. What is sent from py file
  2. What is show on elements tab on webpage
  3. 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 ()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading