0

I haven't dealt a lot with JSON strings in JavaScript and despite my research I can't figure my way around this simple problem. Here is my issue:

My JSON result:

[{
    "Id": "7884",
    "name": "Some Name",
    "location": {
        "distance": 3.2988,
        "geoCode": {
            "latitude": "Y",
            "longitude": "X"
        },
        "address": {
            "street": "14706 E Example Ave.",
            "state": "CA",
            "city": "Hollywood",
            "country": "USA",
            "postalCode": "99999"
        }
    }
}]

Now I parse and iterate :

var obj = JSON.parse(result);

alert(obj[0].Id);

This works great for higher level parts of the string.

However I don't know how to get into the "address" section of the string. I tried obj[0].address.street, obj[0].address[street] and even obj[0].address[0] to no avail.

Can someone direct me to the proper way to dig down to street level?

1 Answer 1

6

You should pass through location object since the address is inside it :

obj[0].location.address.street

Hope this helps.


var obj =[{
    "Id": "7884",
    "name": "Some Name",
    "location": {
        "distance": 3.2988,
        "geoCode": {
            "latitude": "Y",
            "longitude": "X"
        },
        "address": {
            "street": "14706 E Example Ave.",
            "state": "CA",
            "city": "Hollywood",
            "country": "USA",
            "postalCode": "99999"
        }
    }
}];

$('#result').text(obj[0].location.address.street);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='result'></span>

Sign up to request clarification or add additional context in comments.

3 Comments

Oh dang! I missed the "location" hierarchy! Thanks Zakaria!
@Zak you can also access a property from a object that inherits from another object like this: obj[0]['location']['address']['street'].. this can also work to reference properties you don't know but use variables to refer the properties
Thanks @nosthertus for your intervention/suggestion and Yes it will work too.

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.