2

I have the following json data in a Javascript variable result:

[
Object { id="3443", name="Jack", date3="261"},
Object { id="50942", name="Mary", date1="12"}, 
Object { id="2524", name="Paul", date3="163"}
]

How can I access the name and dates values with Javascript?

The json data is produced by a php script I wrote. I am not sure how to be able to name the 'ojbect' which might actually help.


After reading the first comments I realized I actually forgot to use jsonencode before sending the data. So the object above was a php array and not a json encoded object.

2
  • 1
    To clarify, do you know the names of the properties? Commented Jun 13, 2011 at 11:29
  • 1
    That's definitely not valid JSON. You can't have = follow an Object property id. Also, there is no way to access your dates in an automated fashion, because there is an inconsistency between the property ids. E.g. date3 vs. date1. Commented Jun 13, 2011 at 11:39

2 Answers 2

2

try:

alert(your_variable[0].id); // 3443
alert(your_variable[1].id); // 50942
alert(your_variable[2].id); // 2524
Sign up to request clarification or add additional context in comments.

Comments

2

If you know the names of the properties then look into the parseJSON method exposed by jQuery. This enables you to map the properties to a type, of sorts, such as:

var results = jQuery.parseJSON(jsonData);
for (int i = 0; i < results.length; i++) {
    alert(results[i].name + ":" + results[i].date);
}

You may need to tweak the inputs and exact use of the outputs in accordance with your data and requirements.

2 Comments

You don't need jQuery to parse JSON. Behind the scenes, jQuery just uses JSON.parse(), which most modern browsers support, or an eval-style Function(). If you don't want to use jQuery but you want cross browser support, you can use Douglas Crockford's compatibility implementation, available from json.org.
@Andy E: Thanks for the information - very useful, and something I didn't know.

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.