0

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
                }
            },
Matt Jameson
  • 217
  • 1
  • 8
  • 21

2 Answers2

1

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

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

Wojciech Bednarski
  • 6,033
  • 9
  • 49
  • 73
1

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.

Tamas
  • 3,254
  • 4
  • 29
  • 51
  • it seems ive had to parse the json to access it. – Matt Jameson Jan 11 '13 at 15:06
  • I dont understand- I can access it using routeMapping.users[0]firstName once parsed, but I dont want to parse it. I want to access the original json from the var routeMapping, but routeMapping.users[0]firstName doesnt work on it – Matt Jameson Jan 11 '13 at 15:15
  • You have a missing `.` in `routeMapping.users[0].firstName`. – Tamas Jan 11 '13 at 15:18
  • If you have to parse the json *string* then you can make a json objest using JSON.parse(jsonString); [link](http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript) But it looks like that you already have a json object. – Tamas Jan 11 '13 at 15:20
  • @MattJameson you don't need to parse anything, as you wrote in the question you have variable pointing to JSON. – Wojciech Bednarski Jan 11 '13 at 15:21
  • @tamas ok so what if the Json looks like this in the route mapping var: {"b":[{"Ya":53.388639,"Za":-1.4785248000000593},{"Ya":53.39310538272831,"Za":-1.464529037475586}],"gm_accessors_":{"length":null},"length":2,"gm_bindings_":{"length":{}} How would I access the first "Ya" – Matt Jameson Jan 11 '13 at 15:35