0

I hava a JSON Object in my javascript code that is like :

{"0" : "Jul 09, 2012 05:05 PM", "3" : "Jul 09, 2012 05:08 PM"}

I have decoded this JSON using

var jsonObj = eval('(' + {/literal}{$json}{literal} + ')');

I can access values using

jsonObj[i]

but this gives me an error if i access jsonObj[2] since it is not in my json.

So i wish to have a way to access first part of JSON i.e. the key part. so that i store them in an array in JS and loop through them.

1
  • do you want to use jQuery framework? $.parseJSON (json). Commented Jul 10, 2012 at 1:06

3 Answers 3

2

eval is evil. Anyway, if you want to loop through the properties ('keys') of your json, you can do

for(key in jsonObj) {
   if(jsonObj.hasOwnProperty(key)) {
     //do something with the values
     // jsonObj[key] 
   }
}
Sign up to request clarification or add additional context in comments.

3 Comments

why is that evil ? Also your thing worked for me. Thanks Vishal
@user1290495: It's "evil" because the eval method will execute anything that's in the string, so if it contained script, that would run. A JSON parser on the other hand will only accept a string that actually contains only JSON.
Exactly what guffa said. Also, the additional requirement is the fact that the 'json string' is expected to be near perfect and will cause problems if there are even small mistakes. So its always better to use an external library like jquery to do this for you (jQuery.parseJSON)
0
if (jsonObj.hasOwnProperty('2')) {

}

Comments

0

Modern browsers have the "static" method Object.keys(). There is a shim for older browsers. Then you can loop over the returned array of keys, or use .indexOf() or .inArray() if you are using most frameworks.

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.