Javascript实现复杂Json数据展平

今天用到一个 json 数据展平的需求,研究了一下,最终代码如下,实现任意层数的json嵌套数据展平。

核心代码实现:

$.extend({
  /**
    * 展平 JSON 对象
    * @param {*} obj 
    * @param {*} res 
    * @param {*} extraKey 
    * @returns 
    */
   flattenJSON: function (obj = {}, res = {}, extraKey = '') {
       if (!obj) {
           // null or undefined
           res[extraKey] = null;
           return;
       }
   
       var objType = typeof obj;
       if (objType !== 'object') {
           res[extraKey] = obj;
           return;
       }
   
       if (extraKey.length > 0)
           extraKey += ".";
   
       for (key in obj) {
           var type = typeof obj[key];
           //    console.log([key, obj[key], type])
           if (type !== 'object') {
               res[extraKey + key] = obj[key];
           } else {
               // object
               if (obj[key] == null) {
                   res[extraKey + key] = null;
               } else {
                   if (obj[key].constructor === Array) {
                       for (i in obj[key]) {
                           // res[extraKey +key+ "[" + i + "]"] = obj[key][i];
                           $.flattenJSON(obj[key][i], res, `${extraKey}${key}\[${i}\]`);
                       }
                   } else {
                       $.flattenJSON(obj[key], res, `${extraKey}${key}`);
                   }
               }
           };
       };
       return res;
   }
});

测试数据:

var demo =  {
    "name": "韩梅梅",
    "country": "中国",
    "age": null,
    "addr": {
        "prov": "BJ",
        "street": "鼓楼大街",
        "home": "智慧家园1号"
    },
    "fav": [
        "code",
        "movie",
        {
            "qq": "10542845",
            "phone": "87855145",
            "scores": [
                65,
                85.5,
                75.5,
                80.5
            ]
        }
    ]
}

测试代码:

var flatten_json = $.flattenJSON(demo);
console.log(flatten_json)

结果:

{
    "name": "韩梅梅",
    "country": "中国",
    "age": null,
    "addr.prov": "BJ",
    "addr.street": "鼓楼大街",
    "addr.home": "智慧家园1号",
    "fav[0]": "code",
    "fav[1]": "movie",
    "fav[2].qq": "10542845",
    "fav[2].phone": "87855145",
    "fav[2].scores[0]": 65,
    "fav[2].scores[1]": 85.5,
    "fav[2].scores[2]": 75.5,
    "fav[2].scores[3]": 80.5
}
# js   javascript   json   flatten  

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×