mynameisbutt
mynameisbutt

Reputation: 173

Accessing values of a JSON-encoded object

I am sending a JSON encoded array from my controller to my view page. I am doing this on my view page to get the data:

 function () {
     $.get('http://localhost/Location/loc', function(data){
         alert(data[0].message);
     });
 }

The data is like this

 {"message":"hello!"}

I am alerting the value of message but my alert giving me undefined. My question is how can I access values of JSON array?

I am new to JSON so I don't know much about JSON.

Upvotes: 1

Views: 810

Answers (3)

srain
srain

Reputation: 9082

OK, if this does not work:

function () {
     $.get('http://localhost/Location/loc', function(data){
         alert(data.message);
     });
}

try this:

function () {
     $.get('http://localhost/Location/loc', function(data){
         alert(data.message);
     }, 'json');
}

Upvotes: 0

rink.attendant.6
rink.attendant.6

Reputation: 46208

Try changing your function to:

function () {
     $.get('http://localhost/Location/loc', function(data){
         alert(data.message);
     }, 'json');
}

This is because jQuery probably doesn't know that the response data is JSON, so it's assuming that it's plaintext. You can explicitly specify it in $.get as the last parameter as in the revised code, or configure your server to send the response with the HTTP Content-Type header of application/json.

I'm assuming this because message is not a property of a String and that's why you're getting undefined.

Alternatively, you may use $.getJSON:

function () {
     $.getJSON('http://localhost/Location/loc', function(data){
         alert(data.message);
     });
}

Also note that I have changed the alert to data.message. See Knaģis' answer for explanation.

Upvotes: 1

Knaģis
Knaģis

Reputation: 21475

You data contains a single object, not an array.

In your case use alert(data.message); instead.

An array is defined using [] brackets, for example [{message:"hello"}, {message:"world"}] is an array with two objects in it.

Upvotes: 1

Related Questions