0

I am performing a get request to a url that returns a simple JSON object.

Here is the URL: http://live.albiononline.com/status.txt

As you can see it is a text file and it's content-type header is text/plain. When I receive the body log it, it is:

{ "status": "online", "message": "All good." }

But when I try to log, body.status it is undefined. When I do var data = JSON.parse(body); then console.log(data.status); I get:

undefined:1
{ "status": "online", "message": "All good." }
^

SyntaxError: Unexpected token  in JSON at position 0

Any idea what's happening? I assume it has something to do with the fact it's pulling from a .txt file?

UPDATE:

request('http://live.albiononline.com/status.txt', function (error, response, body) {
            if (!error && response.statusCode == 200) {
                console.log(body); // { "status": "online", "message": "All good." }
                console.log(body.status); // undefined
            }
        });
6
  • It's already JSON object. You don't need to parse Commented Feb 16, 2017 at 6:41
  • In my question I said, 'But when I try to log, body.status it is undefined.' Commented Feb 16, 2017 at 6:42
  • can you show me your code once Commented Feb 16, 2017 at 6:45
  • added code to question Commented Feb 16, 2017 at 6:48
  • Try doing JSON.parse(JSON.stringify(body)).status Commented Feb 16, 2017 at 6:57

1 Answer 1

1

The reason is because the output is not a stringified JSON object, it's just a normal string.

The output I got while working on your example code:

'{ "status": "online", "message": "All good." }\r\n'

A real JSON string wouldn't have extra spaces and escape characters at the end.

Solution:

x=x.trim(); // trimming off the \r\n
var output = JSON.parse(x); // parsing the JSON
Sign up to request clarification or add additional context in comments.

3 Comments

Hmm. So how do I parse it as an object?
This is the answer, trim off the \r\n before JSON.parse()
You're a life saver. Thank you very much!

Your Answer

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