Matt Jameson
Matt Jameson

Reputation: 217

json from javascript variable

I have a vaiable 'routeMapping' which stores JSON dynamically.

if the Json turns out to be the example below, how would I access it:

{"users":[
            {
                "firstName":"Ray",
                "lastName":"Villalobos",
                "joined": {
                    "month":"January",
                    "day":12,
                    "year":2012
                }
            },

Upvotes: 0

Views: 76

Answers (2)

Tamas
Tamas

Reputation: 3442

If you have the json in a javascript environment, i.e. in a browser then you can treat it as a javascipt object. E.g.

routeMapping.users[0].firstName

To understand more deeply how to access individual fields, you can use the javascript console of the browser. (E.g. chrome or firefox.) First assign the json (javascript object) to a variable and the print the value:

var routeMapping = {"users":[
        {
            "firstName":"Ray",
            "lastName":"Villalobos",
            "joined": {
                "month":"January",
                "day":12,
                "year":2012
            }
        }]};
alert(routeMapping.users[0].firstName);

Then you can start experimenting what kind of access works in the next line of the console. The browser even give you suggestions for that.

If you have the json value in another language (e.g. java) then you can use JSON libraries to parse and access the values within the JSON expression.

Upvotes: 1

Wojciech Bednarski
Wojciech Bednarski

Reputation: 6373

Since JSON is valid JavaScript Object you can access it via dot nottation like:

routeMapping.users[0].firstName it should give you Ray

Upvotes: 1

Related Questions