Francesco
Francesco

Reputation: 25239

Is it possible to iterate through a JSON to find if a property exists?

I'm trying to do an experiment with google API geolocation.

and I noticed the JSON is not always the same: sometimes the address is a child of a property, sometimes it is not.

For example, if I want to extract for instance the value of PostalCode, it's sometimes:

...SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber

And sometimes is:

...AdministrativeArea.DependentLocality.Locality.PostalCode.PostalCodeNumber

There is no way to know the exact path ot the value. How can I find the value of PostalCodeNumber independently of its parents?

Upvotes: 1

Views: 140

Answers (2)

Dampsquid
Dampsquid

Reputation: 2474

put this on JSFiddle for you to try

function GetPropIn( obj, prop )
{
    for( sProperty in obj )
    {
        if( obj.hasOwnProperty( sProperty ) )
        {
            if( sProperty == prop )
            {
                return( obj[sProperty] );
            }
            else
            {
                if( typeof(obj[sProperty]) == "object" )
                {
                    var res = GetPropIn( obj[sProperty], prop );
                    if( res )
                    {
                        return( res );
                    }
                }
            }
        }
    }    
}

Upvotes: 0

glortho
glortho

Reputation: 13200

Try the inJSON plugin here: http://danconnor.com/search-for-a-key-in-json-with-jquery-$.injson.html

NOTE: I thought I saw jQuery tagged here. Did you remove it or am I seeing things? Anyway, it would be easy to convert this to non-jQuery. It's a simple recursive function.

Upvotes: 1

Related Questions