遍历JavaScript中的JSON对象

时间:2018-09-02 14:19:40

标签: javascript json

我有一个奇怪的JSON对象。我不确定如何对其进行迭代以获取值。

我可以读取一个特定的值,但是却无所适从。

 var sku_object = {
   "SkuDevices": {
      "cb_skus": [
         {
            "XCZU9EG-1E": [
               {
                  "x_speed_alias": [
                     {
                        "$": 1
                     }
                  ],
                  "x_speed": [
                     {
                        "$": 1
                     }
                  ],
                  "device_speed": [
                     {
                        "$": "1REL"
                     }
                  ],
                  "hardware_product": [
                     {
                        "$": "XCZU9EG"
                     }
                  ],
                  "device_grade": [
                     {
                        "$": "E"
                     }
                  ],
                  "status": [
                     {
                        "$": "Active"
                     }
                  ]
               }
            ],
            "XCZU9EG-2I-4522": [
               {
                  "x_speed": [
                     {
                        "$": 2
                     },
                     {
                        "$": 2
                     }
                  ],
                  "x_speed_alias": [
                     {
                        "$": 2
                     }
                  ],
                  "spec_class": [
                     {
                        "$": "SCD"
                     }
                  ],
                  "device_speed": [
                     {
                        "$": "2REL"
                     }
                  ],
                  "x_spec_suffix": [
                     {
                        "$": 4522
                     }
                  ],
                  "spec_name": [
                     {
                        "$": "SCD4522"
                     }
                  ],
                  "hardware_product": [
                     {
                        "$": "XCZU9EG"
                     }
                  ],
                  "x_silicon_stage": [
                     {
                        "$": "PROD"
                     }
                  ],
                  "device_grade": [
                     {
                        "$": "I"
                     }
                  ],
                  "status": [
                     {
                        "$": "Active"
                     }
                  ]
               }
            ]
         }
      ],
      "device": [
         {
            "$": "ZU9EG"
         }
      ]
   }
}

alert (sku_object.SkuDevices["cb_skus"][0]["XCZU9EG-1E"][0]["device_speed"][0]["$"])

如果您看到最后一行,我可以读取一个特定的值。

现在cb_skus下-> XCZU9EG-1E和XCZU9EG-2I-4522不同,可以是任何东西。

再次根据XCZU9EG-2I-4522,属性的数量有所不同。

到目前为止我只能思考:

 for (var i = 0, len = sku_object.XxpubSkuDeviceCollection.cb_skus.length; i < len; ++i) {
     var ss= sku_object.XxpubSkuDeviceCollection.cb_skus[i];
     alert (ss["XCZU9EG-1E"][0]["device_speed"][0]["$"])
 }

这实际上并没有结束。还有如何获取“ device_speed”之类的密钥?

我应该添加,我尝试对其进行迭代的原因是使用奇怪的$符号来构建JSON对象。像这样:

{
    "device" : "zu9eg",
    "cb_skus" : {
            "XCZU9EG-1E" : {"hardware_product" : "XCZU9EG",
                            "device_speed" : "1REL",
                            "x_speed" : "1",
                            "device_grade" : "E",
                            "status" : "active"
            },
            "XCZU9EG-2I-4522" : {"hardware_product" : "XCZU9EG",
                                 "device_speed" : "2REL",
                                 "x_speed" : "2",
                                 "x_speed_alias" : "2",
                                 "device_grade" : "I",
           }
    }
}

2 个答案:

答案 0 :(得分:1)

由于给定数据的奇怪的数组/对象嵌套性质,您需要映射数组并从不规则的深度游泳最终键的海洋中探出属性。

然后使用嵌套的属性来形成新对象,以简化仅两层的属性。

function final(a) {
    return '$' in a[0]
        ? a[0].$
        : Object.assign(
            ...a.map(o =>
                Object.assign(...Object.entries(o).map(([k, v]) => ({ [k]: final(v) })))
            )
        );
}

var sku_object = { SkuDevices: { cb_skus: [{ "XCZU9EG-1E": [{ x_speed_alias: [{ $: 1 }], x_speed: [{ $: 1 }], device_speed: [{ $: "1REL" }], hardware_product: [{ $: "XCZU9EG" }], device_grade: [{ $: "E" }], status: [{ $: "Active" }] }], "XCZU9EG-2I-4522": [{ x_speed: [{ $: 2 }, { $: 2 }], x_speed_alias: [{ $: 2 }], spec_class: [{ $: "SCD" }], device_speed: [{ $: "2REL" }], x_spec_suffix: [{ $: 4522 }], spec_name: [{ $: "SCD4522" }], hardware_product: [{ $: "XCZU9EG" }], x_silicon_stage: [{ $: "PROD" }], device_grade: [{ $: "I" }], status: [{ $: "Active" }] }] }], device: [{ $: "ZU9EG" }] } },
    result = final([sku_object.SkuDevices]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)

如果使用JSON.parse获取对象,则可以使用reviver parameter修改值:

var j = '{"SkuDevices":{"cb_skus":[{"XCZU9EG-1E":[{"x_speed_alias":[{"$":1}],"x_speed":[{"$":1}],"device_speed":[{"$":"1REL"}],"hardware_product":[{"$":"XCZU9EG"}],"device_grade":[{"$":"E"}],"status":[{"$":"Active"}]}],"XCZU9EG-2I-4522":[{"x_speed":[{"$":2},{"$":2}],"x_speed_alias":[{"$":2}],"spec_class":[{"$":"SCD"}],"device_speed":[{"$":"2REL"}],"x_spec_suffix":[{"$":4522}],"spec_name":[{"$":"SCD4522"}],"hardware_product":[{"$":"XCZU9EG"}],"x_silicon_stage":[{"$":"PROD"}],"device_grade":[{"$":"I"}],"status":[{"$":"Active"}]}]}],"device":[{"$":"ZU9EG"}]}}'

var o = JSON.parse(j, (k, v) => v.map ? v[0] : v.$ || v)

console.log( o )


JSON.parse为每个已解析的属性和值对调用reviver函数,返回的结果是要分配给该属性的值。上面的示例重写为更具可读性:

var json = '{"SkuDevices":{"cb_skus":[{"XCZU9EG-1E":[{"x_speed_alias":[{"$":1}],"x_speed":[{"$":1}],"device_speed":[{"$":"1REL"}],"hardware_product":[{"$":"XCZU9EG"}],"device_grade":[{"$":"E"}],"status":[{"$":"Active"}]}],"XCZU9EG-2I-4522":[{"x_speed":[{"$":2},{"$":2}],"x_speed_alias":[{"$":2}],"spec_class":[{"$":"SCD"}],"device_speed":[{"$":"2REL"}],"x_spec_suffix":[{"$":4522}],"spec_name":[{"$":"SCD4522"}],"hardware_product":[{"$":"XCZU9EG"}],"x_silicon_stage":[{"$":"PROD"}],"device_grade":[{"$":"I"}],"status":[{"$":"Active"}]}]}],"device":[{"$":"ZU9EG"}]}}';

var obj = JSON.parse(json, 
  function(key, value) {                               // for each parsed value, 
    if ( Array.isArray(value) ) { return value[0]; }   // if the value is array, return the first item. For example, [1, 2] becomes 1
    else if ( value.hasOwnProperty('$') ) { return value['$']; }    // if the value has a property "$", return it's value. For example, { "$": 1, "a": 2 } becomes 1
    else return value;                                 // otherwise, return the value unchanged for the rest of the values
  }
);

console.log( obj );