-1

I am using $.post() jQuery function. I am getting below data

while I am alerting returned data using code alert(data);.

[{"sn":"2","res_id":"101","res_owner_id":"28","res_address":"uk,london"}]

I would like to get single data value like sn = 2.

I tried with code alert(data[0].sn);

I read below stackoverflow posts.

How can I get value through JSON array like query

Search an array for matching attribute

get one item from an array of name,value JSON

But could not find any solution.

Could anyone help me to get single data??

Thanks

1
  • 1
    what you received is purely string, it is not an object yet. use the parse method to convert it to an object based on json standard. then you can treat it as object and use . (dot) to access the value. Commented Jan 23, 2014 at 13:42

4 Answers 4

3

You can use JSON.parse() on the JSON string to turn it into a JavaScript object.

data = JSON.parse(data);
alert(data[0].sn);

jQuery should be able to do that for you automatically though, if you specify dataType to be json while calling the $.post() method.

Sign up to request clarification or add additional context in comments.

Comments

2

your data seems to be not a JavaScript object (it is string) first convert your data to JavaScript object with JSON.parse(data) then alert(data[0].sn)

7 Comments

sMr has it entirely backwards. It is JSON formatted, it needs converting to a JavaScript array.
@Quentin no if it was a json object at alert message the user should see an message like object [] object.
I think sMr calls a "JavaScript object" a "JSON object", hence the confusion. There is no "JSON object". There is "JSON string" and "JavaScript object". JSON stands for "JavaScript Object Notation".
@Quentin I think you mean Object
@superphonic — I don't. The outside of the JSON text is [] not {}.
|
2

When you run alert, you are getting a string containing your data (and not [Object object] or similar). This means that jQuery hasn't recognised the response as JSON so it hasn't parsed it.

You should fix this on the server by making the response have a Content-Type: application/json HTTP response header.

You could hack this by adding "JSON" as the fourth argument to $.post (to tell jQuery to ignore what the server says the data is and parse it as JSON anyway).

Comments

0

if you are using jQuery, you can use

var new_data = $.parseJSON(data);
alert(new_data[0].sn);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.