Justin D.
Justin D.

Reputation: 4976

JSON Parse error: Unexpected EOF

I am using the following coffeescript code to retrieve json data from my Rails api, parse the json and return the array of object.

 result = Lungo.Service.get('http://localhost:3000/lists.json')
 lists = JSON.parse(result.response).lists

I get this error : JSON Parse error: Unexpected EOF

When I execute the code from the console, everything works fine. The code is parsed. However, it seems that in my code, while result in indeed set to a XMLHttpRequest, its response property, which contains my json formatted data, is empty when accessed like so : result.response.

I searched on Google, but no solution solved my problem.

Example of the response of result = Lungo.Service.get(url) :

result = XMLHttpRequest
|
___>
  constructor: XMLHttpRequestConstructor
  onabort: null
  onerror: null
  onload: null
  onloadend: null
  onloadstart: null
  onprogress: null
  onreadystatechange: function () {if(h.readyState===4){clearTimeout(r);return c(h,f)}}
  readyState: 4
  response: "{"lists":[ *data removed for brevity*]}"
  responseText: "{"lists":[ *data removed for brevity*]}"
  responseType: ""
  responseXML: null
  status: 200
  statusText: "OK"
  upload: XMLHttpRequestUpload
  withCredentials: false
  __proto__: XMLHttpRequestPrototype

Upvotes: 0

Views: 7738

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123563

Lungo.Service methods are asynchronous by default, so .get() will return result before result.response has been received.

It can still appear in the log because some logs are asynchronous as well, so they may not try to read the value until after it's become available.

You can use the "callback function" argument to specify what do with the response once it is available. You can also specify 'json' as the "Mime-type."

Lungo.Service.get('http://localhost:3000/lists.json', function (response) {
    var lists = response.lists;
    // use `lists` here
}, 'json');

Upvotes: 1

Related Questions