www.webdeveloper.com
Results 1 to 6 of 6

Thread: how to access JSON object using variable?

  1. #1
    Join Date
    Nov 2011
    Posts
    22

    how to access JSON object using variable?

    i have a json object as follows

    Code:
    var data={
    "name": "DIV",
    "id": 1,
    "child": [
    {
    "name": "DIV",
    "id": "1.1"
    }
    ]
    }
    if i have a value in a variable like this

    Code:
    var i="child[0]"
    how can i access the specified object from the json object data??
    i tried
    Code:
     data[eval(i)]
    . But it return child undefined.
    How to access the object using variable?

  2. #2
    Join Date
    May 2005
    Location
    Dirty Jersey
    Posts
    1,402
    it's not working because you've misunderstanding what you're actually asking for from the interpreter:

    when defined, your data object looks like this:

    Code:
    {name:"DIV", id:1, child:[{name:"DIV", id:"1.1"}]}
    if you wanted the "child" property of the "data" object, under NORMAL circumstances, you'd type:

    Code:
    data["child"]
    //or
    data.child
    so, when you type (or, by inference, do what you're trying to do)

    Code:
    data["child[0]"]
    you'd get "undefined" because the data object contains a property called "child", but it has no property called "child[0]"

    Code:
    data = {"child[0]": 1234}
    NOW data has a property called "child[0]". NOW this will work:

    Code:
    var i = "child[0]"
    data[i]
    // but data.i won't work because there is no property 'i'
    so to TRULY get "index zero" of the "child" property of the "data" object, you'd have to use this syntax:

    Code:
    data["child"][0]
    and the only way to eval that would be if you had something like

    Code:
    var i = '["child"][0]'
    eval("data"+i)

    1. If you reply to my post, and your reply would then appear directly beneath my post, DON'T QUOTE MY ENTIRE POST!!! IT'S REDUNTANT!!! IT'S ASININE!!!! IT'S REDUNDANTLY ASININE!!!!! DON'T DO IT!!!!
    2. jQuery extends the functionality of JavaScript. If you don't know JavaScript, give up on that jQuery script and learn JavaScript. You'll save yourself a lot of frustration, I promise.
    3. Use the [code][/code] tags. Otherwise, you may be left wondering why no one responded to your eyesore of a thread.


  3. #3
    Join Date
    Nov 2011
    Posts
    22
    yes..."data."+i worked..
    Thanks a lot...

  4. #4
    Join Date
    Dec 2005
    Posts
    2,984
    Whoa, listen to what Angry Black Man (love the name by the way!!) is saying - he's not saying to use eval because you don't need to. He did offer that option as a way to do it, but the proper way to do it, which he also pointed out, is this:

    Code:
    data.child[0];
    //or
    data['child'][0];
    I've switched careers...
    I'm NO LONGER a scientist,
    but now a web developer...
    awesome.

  5. #5
    Join Date
    Nov 2011
    Posts
    22
    ok..now i can fetch a particular element from the existing json object.
    But once i get the element how to add a child node to that element?

  6. #6
    Join Date
    Dec 2005
    Posts
    2,984
    I think you may be missing a good JSON foundation. A JSON string, when eval'd, is simply an object literal in JavaScript. An object literal has properties and these properties have values. That's it. If you come from another programming language then you may say, 'hey, that's an associative array!' or 'hey, that's just a hash!' and for all intents and purposes, you would be correct, that's it. A JSON string is just a multi-dimensional array.

    The properties (or keys) will always be strings (if they were all integers then you'd just be using a single-dimensional array, right?). The values, however, can be many different things. The values can themselves be object literals (or hashes), or they could be arrays, or simple types like strings or integers.

    This is a good example to start from:

    Code:
    var jsonObject = {
    	name	:	'myjsonstring',
    	anObject	:	{
    		carrot	:	'veggie',
    		potato	:	'veggie',
    		apple	:	'fruit',
    		banana	:	'fruit',
    		lettuce	:	'veggie',
    		orange	:	'fruit',
    		celery	:	'veggie',
    		tomato	:	'fruit'
    	},
    	
    	anArray		:	[
    		'apple','tomato','banana','orange'
    	],
    	
    	anArrayOfObjects	:	[
    		{ 
    			property1	:	'value1',	
    			property2	:	'value2'	
    		},
    		{ 
    			property3	:	'value3',	
    			property4	:	'value4'	
    		}
    	],
    	
    	anObjectOfArrays	:	{
    		fruits		:	['apple','tomato','banana','orange'],
    		veggies	:	['carrot','potato','celery','lettuce']
    	}
    
    }
    If you wanted to get the value of the name property of the above you'd simply do this (and you probably already know this):
    Code:
    alert(jsonObject.name);
    If you do this:
    Code:
    alert(jsonObject.anObject);
    You'll get something like [Object object]

    If you do this:
    Code:
    alert(jsonObject.anObject.tomato);
    You'll get fruit.

    If you do this:
    Code:
    alert(jsonObject.anArray)
    You'll get apple,tomato,banana,orange

    If you do this
    Code:
    alert(jsonObject.anArray[3]);
    You'll get orange

    Hopefully that gave you a reasonably good understanding of JSON works.

    If you want to append a child node to this JSON object, how to do it depends what you want to append it to - an array or an object.

    To append it to an object you would just use dot (or square bracket notation)
    Code:
    jsonObject.myNewChild = 'a node';
    //or
    jsonObject['myNewChild'] = 'a node';
    or, if you are adding it to a child object:
    Code:
    jsonObject.anObject.corn = 'veggie';
    //or
    jsonObject.anObject['corn'] = 'veggie';
    If you wanted to append it to an array, then you'd have to use the .push() (http://www.w3schools.com/jsref/jsref_push.asp) method in JavaScript like this:
    Code:
    jsonObject.anArray.push('corn')

    JSON is a very powerful and lightweight notation, the only way to use it properly, though is to have a good foundation in what a JavaScript object literal and a JavaScript array actually are and how they work.

    Good luck!
    I've switched careers...
    I'm NO LONGER a scientist,
    but now a web developer...
    awesome.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles