使用jquery获取json对象中的父对象数

时间:2015-07-22 13:34:53

标签: javascript jquery json

以下是JSON数组,我想得到多个父对象,然后对它们运行循环以获取每个对象值。

它应该给出总计数2,因为我有两个父对象 - canvas0和canvas1。

{"canvas0":
     "{"objects":      
 [{"type":"textbox","originX":"left","originY":"top","left":40,"top":350,"width":200,"height":20.97,"fill":"black","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","text":"ADDRESScanvasPage1","fontSize":16,"fontWeight":"normal","fontFamily":"Helvetica","fontStyle":"","lineHeight":1.16,"textDecoration":"","textAlign":"center","textBackgroundColor":"","styles":{},"minWidth":20}],"background":""}"


,"canvas1":"{"objects":[{"type":"textbox","originX":"left","originY":"top","left":40,"top":350,"width":200,"height":20.97,"fill":"black","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","text":"ADDRESScanvasPage2","fontSize":16,"fontWeight":"normal","fontFamily":"Helvetica","fontStyle":"","lineHeight":1.16,"textDecoration":"","textAlign":"center","textBackgroundColor":"","styles":{},"minWidth":20}],"background":""}"}

1 个答案:

答案 0 :(得分:0)

正如大家所说,你的JSON无效。最小化的相同有效JSON将如下所示。

var json = {
    "canvas0": {
        "objects": [
            {
                "type": "textbox",
                "originX": "left"
            }
        ],
        "background": "#000"
    },
    "canvas1": {
        "objects": [
            {
                "type": "select",
                "originX": "right"
            }
        ]
    }
};

为了能够通过迭代,您不需要计算顶级密钥。而且,JSON对象没有length属性。您需要做的就是使用for...in循环并相应地显示键/值。这是一个如何做到这一点的例子。请记住,这仅适用于您的特定情况,因为循环需要在JSON级别更改时更改。

alert ( "Length of top level keys: " + Object.keys(json).length );

for (var key in json) {

    var canvas = json[key];
    for (var key2 in canvas) {

        if (canvas[key2] instanceof Array) {
            var object = canvas[key2][0];
            for (var key3 in object) {
                alert (key3 + ": " + object[key3]);
            }
        } else {
            alert (key2 + ": " + canvas[key2]);
        }
    }
}

这是一个包含完整代码的working demo