jrn jrn - 1 month ago 8
Javascript Question

Simple JSON stays undefined

I have an AJAX call that get's a simple JSON back on success, writing the returned JSON into the variable named

data
.

The returned JSON has been generated within PHP through:

echo json_encode(array('message'=>0);
.

Back in my javascript console I'm logging the output of
data
with
console.log(data);
. The output is
{"message":0}
, which seems correct.

However, if I try to log
console.log(data.message);
I am getting
message: undefined
.

What am I doing wrong in accessing this pretty basic JSON object?

I've been reading some articles about how to move through JSON object, e.g. https://www.tutorialspoint.com/json/json_overview.htm but I can't find my mistake.

Hopefully you can point me into the right direction :)

Thank you :)

Answer

You have to do JSON.parse(result) first to make it an object, because at the moment you're trying to access message property of a string.

You know there are 2 JSON functions in javascript, right...?

// returns string representation of the object
JSON.stringify(object);

// returns a new object built from the string
JSON.parse(object_stringified); 
Comments