helpisgood
helpisgood

Reputation: 381

Reading JSON data into Javascript

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

Upvotes: 0

Views: 127

Answers (3)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038780

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

Upvotes: 1

John F.
John F.

Reputation: 164

Change this:

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

to this:

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

Upvotes: 0

RemcoGerlich
RemcoGerlich

Reputation: 31260

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

Upvotes: 2

Related Questions