开发者

javascript / jquery using a variable to reference different parts of a json/xml object

I'd like to create a function which can cope with JSON in the following nested format. The keys will change ie conditions - could be anything and the subcondition key could be anything but the structure remains the same.

My function is defined as

  populatePageEditorMenu: function (jsonPath, topLevel, childLevel){  

and called by

 populatePageEditorMenu("http://localhost/data/conditions.json", 'conditions', 'subcondition' );

this allows me to point to different bit of json with different keys with the SAME structure however I cant seem to get the subcondition key to be configurable my syntax is'nt quite right.

With the following JSON

{
    "conditions": [
        {
            "condition": [
                {
                    "name": "TOP",
                    "subcondition": [
                        {
                            "name": "CHILD1"
                        }
                    ]
                }
            ]
        }
    ]
}

I can reference the top level conditions as such using square brackets..

$.getJSON(jsonPath,
                    function(data) {
                        $.each(data[topLevel], function(topentryIndex, entry) {

This works OK !

The problematic subsection doesnt seem to work I had prior to this using paramaterized used the following ... The square brackets dont work here ...

$.each(this.subcondition, function(entryIndex, entry) { ....

I've posted a more complete version on the jsfiddle the JSON can be seen in the C开发者_如何学GoSS view.

Reference - http://jsfiddle.net/wmitchell/QRkxd/


Thanks for looking at this guys apologies it was probably hard for me to explain what I was after.

Basically I wanted to know if I could use variables to represent the fields I was trying to access within an object

I was able to use things like

$.each(data[topLevel], function(topentryIndex, entry) {

Where toplevel was a string rep of a field in the object

and

 this["variablename"]

to do it

Thanks for looking at this. I had a few mistakes in my json also which probably didnt help. Not sure If I should leave this post around or delete it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜