0

Trying to return some JSON code from the server so I can manipulate it within the JavaScript.

However i'm getting the following error:

Uncaught SyntaxError: Unexpected token m in JSON at position 10

Here is my code:

getJSON(url, success) {
      let query = [ 'cars', 'vans', 'bikes' ];

      var xhr = new XMLHttpRequest();
      xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
          if (xhr.status === 200) {
            success(JSON.parse(xhr.responseText));
          } else {
            exit(xhr.responseText);
          }
        }
      };
      xhr.open('GET', url);
      xhr.send();
    }

This is the response I get if I just console.log the xhr.responseText:

[
  {
    make: 'VOLVO'
  },
  {
    make: 'AUDI'
  },
  {
    make: 'VOLKSWAGON'
  },
]
Martyn Ball
  • 4,679
  • 8
  • 56
  • 126
  • 6
    This is not valid JSON. JSON can't have trailing commas and always requires double quotes for property names and strings. – nils May 18 '17 at 11:08
  • Crap, my mistake. I messed up the JSON – Martyn Ball May 18 '17 at 11:11
  • 2
    You may want to catch the error in order to fail gracefully when server returns invalid data. – Álvaro González May 18 '17 at 11:11
  • You need to wrap your strings in quotes. Your _"make"_ key is missing the opening quote, that is what the console is telling you. It is expecting a `"`, but it found an `m`. Voted to close, because this is a data issue, not a coding issue. – Mr. Polywhirl May 18 '17 at 11:39

1 Answers1

1

The object you are trying to parse is a valid JavaScript object, but not a valid JSON.

keys should be strings, which are defined as

a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes

You should not use any trailing comma (see Can you use a trailing comma in a JSON object?).

A proper JSON string for your object should be:

let s = '[ {"make": "VOLVO"}, {"make": "AUDI"}, {"make": "VOLKSWAGON"} ]';

Code could be fixed to detect this problem:

getJSON(url, success) {
    let query = [ 'cars', 'vans', 'bikes' ];
    let xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                try {
                    let parsedJSON = JSON.parse(xhr.responseText);
                    success(parsedJSON);
                } catch (e) {
                    if (e instanceof SyntaxError === true) {
                        // Problem with the format of the JSON string.
                    } else {
                        // Other error
                    }
                }
            } else {
                exit(xhr.responseText);
            }
        }
    };

    xhr.open('GET', url);
    xhr.send();
}

Misc. resources:

Community
  • 1
  • 1
dashdashzako
  • 1,268
  • 15
  • 24