user971956
user971956

Reputation: 3208

How to access an anonymous JSON attribute?

I have the following JSON:

{
    "Files": {
             "Lines": {
                    "198": {
                           "firstline": "sometext"
                    }
             }
    }
}

and the value "198" is dynamic and changes. How can I access the "firstline" property easily without knowing "198" in the following code:

var schema = JSON.parse(fileContents); 
console.log(schema.Files.Lines.????.firstline);

Upvotes: 2

Views: 5839

Answers (4)

Šime Vidas
Šime Vidas

Reputation: 185933

Just do this:

schema.Files.Lines.properties[0].firstline

Live demo: http://jsfiddle.net/KBj2G/

(Yes, the 'properties' getter has to be implemented manually... )

Upvotes: 1

Dennis
Dennis

Reputation: 32598

If you don't know what the key will be, it might be useful to return your data as an array:

{
    "Files": {
        "Lines": [{
            "id": "198",
            "firstline": "sometext"}]
    }
}

var schema = JSON.parse(fileContents); 
console.log(schema.Files.Lines[0].firstline); //sometext

Upvotes: 1

benekastah
benekastah

Reputation: 5711

A few lines will do it:

var obj = JSON.parse(your_json);
var lines = obj.Files.Lines;
var keys = Object.keys(lines);
var keyICareAbout = keys[0];
var info  = lines[keyICareAbout];

Note: This solution relies on some newer javascript features. For JSON to work in all browsers, you will need Douglas Crockford's json2.js from here. For Object.keys to work in all browsers, use this shim from Mozilla's JS docuentation:

if(!Object.keys) Object.keys = function(o){
 if (o !== Object(o))
      throw new TypeError('Object.keys called on non-object');
 var ret=[],p;
 for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p);
 return ret;
}

Edit: Try this jsfiddle. Now updated with cross browser compatability measures and accessing data dynamically.

Upvotes: 5

Dominic Barnes
Dominic Barnes

Reputation: 28429

Unless you decide to specifically use an Array at the Lines level, there is no way to guarantee what order they will come out it.

Using for..in or Object.keys, you can enumerate the properties, and just exit out of the loop on the first iteration. But again, there is no guarantee what order they will come out in, it depends upon the implementation. (although many times, it'll be what you expect)

Upvotes: 1

Related Questions