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
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).

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);

Comments

0

Change this:

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

to this:

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

Comments

Your Answer

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.