Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting first JSON property

Tags:

Is there a way to get the name of the first property of a JSON object?

I'd like to do something like this:

var firstProp = jsonObj[0]; 

edit: I'm getting a JSON object which hold categories of arrays with image URLs.

like so:

{   "category1":["image/url/1.jpg","image/url/2.jpg"],   "category2":["image/url/3.jpg","image/url/4.jpg"] } 

I am then iterating through the object to insert the images, and all I really wanted was an elegant way to see which category was inserted first. At first I just did

for (var cat in images) {     if (i==0) firstCat = cat;     ... } 

But that some how "felt" ugly... So it was basically just a question of elegance.

like image 334
peirix Avatar asked Jul 12 '09 19:07

peirix


People also ask

How do you get the first JSON object in Python?

Make any Object array ( req ), then simply do Object. keys(req)[0] to pick the first key in the Object array.

Does the order of JSON properties matter?

Any error or exception? The JSON RFC (RFC 4627) says that order of object members does not matter.


2 Answers

console.log(jsonObj[Object.keys(jsonObj)[0]]); 
like image 132
Rihard Novozhilov Avatar answered Jan 08 '23 11:01

Rihard Novozhilov


The order of the properties of an object are not guaranteed to be the same as the way you put them in. In practice, however, all major browsers do return them in order. So if you're okay with relying on this...

var firstProp; for(var key in jsonObj) {     if(jsonObj.hasOwnProperty(key)) {         firstProp = jsonObj[key];         break;     } } 

Also note that there's a bug in Chrome regarding the ordering, in some edge cases it doesn't order it in the way they were provided. As far as it changing in the future, the chances are actually pretty small as I believe this is becoming part of the standard so if anything support for this will only become official.

All things considered, though, if you really, really, absolutely, positively, want to be sure it's going to be in the right order you need to use an array. Otherwise, the above is fine.

Related question: Elements order - for (… in …) loop in javascript

like image 33
Paolo Bergantino Avatar answered Jan 08 '23 11:01

Paolo Bergantino