0

I have the following piece of code in a function to read in a JSON file:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
 if (this.readyState == 4 && this.status == 200) {
 myObj = this.responseText;
 console.log(myObj);
 JSON.parse(myObj); // error is here
 }
};
xmlhttp.open("GET", "music-data.json", true);
xmlhttp.send();

The JSON data is coming locally from the same folder as my html/css/js files, and is structured as:

window.MUSIC_DATA = {
 "list1": [
 {
 data here...
 },
 ],
 "list2": [
 { data here...
 ...
}

I am unable to parse my object and extract what I need from list1 and list2 and get an error with the existing code:

Uncaught SyntaxError: Unexpected token w in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.xmlhttp.onreadystatechange
clearlight
12.7k11 gold badges61 silver badges82 bronze badges
asked Jan 18, 2017 at 8:34
1
  • 2
    remove window.MUSIC_DATA = part in your json file Commented Jan 18, 2017 at 8:35

3 Answers 3

2

The problem is with

window.MUSIC_DATA =

That's not JSON, it's JavaScript. Remove that from the file so that only the value is left, and it may work (or there may be other problems with the file).

answered Jan 18, 2017 at 8:35
Sign up to request clarification or add additional context in comments.

Comments

1

As others have stated you need to fix your server side file to be a valid JSON. If you have no control over the contents of this file and want to avoid string manipulation routines here's an alternative approach that you could use:

var s = document.createElement('script');
s.src = 'music-data.json';
s.async = true;
s.onreadystatechange = s.onload = function() {
 if (!s.readyState || /loaded|complete/.test(s.readyState)) {
 var myObj = window['MUSIC_DATA'];
 console.log(myObj);
 alert(myObj.list1);
 alert(myObj.list2);
 ...
 }
};
document.querySelector('head').appendChild(s);
answered Jan 18, 2017 at 8:42

Comments

0

Change this:

window.MUSIC_DATA = {
 "list1": [
 {
 data here...
 },
 ],
 "list2": [
 { data here...
 ...
}

to this:

{
 "list1": [
 {
 data here...
 },
 ],
 "list2": [
 { data here...
 ...
}
answered Jan 18, 2017 at 8:37

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.