压缩/取消嵌套嵌套JSON对象的最快方法

时间:2013-09-30 16:05:46

标签: javascript algorithm

我将一些代码放在一起,以展平和展开复杂/嵌套的JSON对象。它有效,但它有点慢(触发'长脚本'警告)。

对于我想要的扁平名称“。”作为数组的分隔符和[INDEX]。

示例:

un-flattened | flattened
---------------------------
{foo:{bar:false}} => {"foo.bar":false}
{a:[{b:["c","d"]}]} => {"a[0].b[0]":"c","a[0].b[1]":"d"}
[1,[2,[3,4],5],6] => {"[0]":1,"[1].[0]":2,"[1].[1].[0]":3,"[1].[1].[1]":4,"[1].[2]":5,"[2]":6}

我创建了一个基准,可以模拟我的用例http://jsfiddle.net/WSzec/

  • 获取嵌套的JSON对象
  • 扁平化
  • 查看它并在展平时修改它
  • 将其恢复原状的原始嵌套格式

我想要更快的代码:为了澄清,在IE 9 +,FF 24+和Chrome中,完成JSFiddle基准测试(http://jsfiddle.net/WSzec/)的代码明显更快(~20%+会很好) 29 +

以下是相关的JavaScript代码:当前最快:http://jsfiddle.net/WSzec/6/

JSON.unflatten = function(data) {
    "use strict";
    if (Object(data) !== data || Array.isArray(data))
        return data;
    var result = {}, cur, prop, idx, last, temp;
    for(var p in data) {
        cur = result, prop = "", last = 0;
        do {
            idx = p.indexOf(".", last);
            temp = p.substring(last, idx !== -1 ? idx : undefined);
            cur = cur[prop] || (cur[prop] = (!isNaN(parseInt(temp)) ? [] : {}));
            prop = temp;
            last = idx + 1;
        } while(idx >= 0);
        cur[prop] = data[p];
    }
    return result[""];
}
JSON.flatten = function(data) {
    var result = {};
    function recurse (cur, prop) {
        if (Object(cur) !== cur) {
            result[prop] = cur;
        } else if (Array.isArray(cur)) {
             for(var i=0, l=cur.length; i<l; i++)
                 recurse(cur[i], prop ? prop+"."+i : ""+i);
            if (l == 0)
                result[prop] = [];
        } else {
            var isEmpty = true;
            for (var p in cur) {
                isEmpty = false;
                recurse(cur[p], prop ? prop+"."+p : p);
            }
            if (isEmpty)
                result[prop] = {};
        }
    }
    recurse(data, "");
    return result;
}

编辑1 将上述内容修改为目前最快的@Bergi实现。另外,使用“.indexOf”而不是“regex.exec”在FF中快20%左右,但在Chrome中慢20%;所以我会坚持使用正则表达式,因为它更简单(这是我尝试使用indexOf替换正则表达式http://jsfiddle.net/WSzec/2/)。

编辑2 基于@Bergi的想法,我设法创建了一个更快的非正则表达版本(在FF中快3倍,在Chrome中快10%)。 http://jsfiddle.net/WSzec/6/在这个(当前的)实现中,键名的规则很简单,键不能以整数开头或包含句点。

示例:

  • {“foo”:{“bar”:[0]}} =&gt; { “foo.bar.0”:0}

编辑3 添加@AaditMShah的内联路径解析方法(而不是String.split)有助于改善不平坦的性能。我对整体性能提升感到非常满意。

最新的jsfiddle和jsperf:

http://jsfiddle.net/WSzec/14/

http://jsperf.com/flatten-un-flatten/4

17 个答案:

答案 0 :(得分:181)

这是我更短的实现:

Object.unflatten = function(data) {
    "use strict";
    if (Object(data) !== data || Array.isArray(data))
        return data;
    var regex = /\.?([^.\[\]]+)|\[(\d+)\]/g,
        resultholder = {};
    for (var p in data) {
        var cur = resultholder,
            prop = "",
            m;
        while (m = regex.exec(p)) {
            cur = cur[prop] || (cur[prop] = (m[2] ? [] : {}));
            prop = m[2] || m[1];
        }
        cur[prop] = data[p];
    }
    return resultholder[""] || resultholder;
};

flatten变化不大(我不确定您是否真的需要isEmpty个案例):

Object.flatten = function(data) {
    var result = {};
    function recurse (cur, prop) {
        if (Object(cur) !== cur) {
            result[prop] = cur;
        } else if (Array.isArray(cur)) {
             for(var i=0, l=cur.length; i<l; i++)
                 recurse(cur[i], prop + "[" + i + "]");
            if (l == 0)
                result[prop] = [];
        } else {
            var isEmpty = true;
            for (var p in cur) {
                isEmpty = false;
                recurse(cur[p], prop ? prop+"."+p : p);
            }
            if (isEmpty && prop)
                result[prop] = {};
        }
    }
    recurse(data, "");
    return result;
}

在大约一半的时间里他们run your benchmark(Opera 12.16:〜900ms而不是〜1900ms,Chrome 29:~800ms而不是~1600ms)。

答案 1 :(得分:19)

我写了两个函数给flattenunflatten一个JSON对象。


<强> Flatten a JSON object

var flatten = (function (isArray, wrapped) {
    return function (table) {
        return reduce("", {}, table);
    };

    function reduce(path, accumulator, table) {
        if (isArray(table)) {
            var length = table.length;

            if (length) {
                var index = 0;

                while (index < length) {
                    var property = path + "[" + index + "]", item = table[index++];
                    if (wrapped(item) !== item) accumulator[property] = item;
                    else reduce(property, accumulator, item);
                }
            } else accumulator[path] = table;
        } else {
            var empty = true;

            if (path) {
                for (var property in table) {
                    var item = table[property], property = path + "." + property, empty = false;
                    if (wrapped(item) !== item) accumulator[property] = item;
                    else reduce(property, accumulator, item);
                }
            } else {
                for (var property in table) {
                    var item = table[property], empty = false;
                    if (wrapped(item) !== item) accumulator[property] = item;
                    else reduce(property, accumulator, item);
                }
            }

            if (empty) accumulator[path] = table;
        }

        return accumulator;
    }
}(Array.isArray, Object));

<强>性能

  1. 它比Opera目前的解决方案更快。目前的解决方案在Opera中慢了26%。
  2. 它比Firefox中的当前解决方案更快。目前的解决方案在Firefox中慢了9%。
  3. 它比Chrome中的当前解决方案更快。目前的解决方案在Chrome中慢了29%。

  4. <强> Unflatten a JSON object

    function unflatten(table) {
        var result = {};
    
        for (var path in table) {
            var cursor = result, length = path.length, property = "", index = 0;
    
            while (index < length) {
                var char = path.charAt(index);
    
                if (char === "[") {
                    var start = index + 1,
                        end = path.indexOf("]", start),
                        cursor = cursor[property] = cursor[property] || [],
                        property = path.slice(start, end),
                        index = end + 1;
                } else {
                    var cursor = cursor[property] = cursor[property] || {},
                        start = char === "." ? index + 1 : index,
                        bracket = path.indexOf("[", start),
                        dot = path.indexOf(".", start);
    
                    if (bracket < 0 && dot < 0) var end = index = length;
                    else if (bracket < 0) var end = index = dot;
                    else if (dot < 0) var end = index = bracket;
                    else var end = index = bracket < dot ? bracket : dot;
    
                    var property = path.slice(start, end);
                }
            }
    
            cursor[property] = table[path];
        }
    
        return result[""];
    }
    

    <强>性能

    1. 它比Opera目前的解决方案更快。目前的解决方案在Opera中慢了5%。
    2. 它比Firefox中的当前解决方案慢。我的解决方案在Firefox中慢了26%。
    3. 它比Chrome中的当前解决方案慢。我的解决方案在Chrome中慢了6%。

    4. <强> Flatten and unflatten a JSON object

      总体而言,我的解决方案与当前解决方案的表现相同甚至更好。

      <强>性能

      1. 它比Opera目前的解决方案更快。目前的解决方案在Opera中慢了21%。
      2. 它与Firefox中的当前解决方案一样快。
      3. 它比Firefox中的当前解决方案更快。目前的解决方案在Chrome中慢了20%。

      4. 输出格式

        展平对象使用对象属性的点表示法和数组索引的括号表示法:

        1. {foo:{bar:false}} => {"foo.bar":false}
        2. {a:[{b:["c","d"]}]} => {"a[0].b[0]":"c","a[0].b[1]":"d"}
        3. [1,[2,[3,4],5],6] => {"[0]":1,"[1][0]":2,"[1][1][0]":3,"[1][1][1]":4,"[1][2]":5,"[2]":6}
        4. 在我看来,这种格式比仅使用点符号更好:

          1. {foo:{bar:false}} => {"foo.bar":false}
          2. {a:[{b:["c","d"]}]} => {"a.0.b.0":"c","a.0.b.1":"d"}
          3. [1,[2,[3,4],5],6] => {"0":1,"1.0":2,"1.1.0":3,"1.1.1":4,"1.2":5,"2":6}

          4. <强>优点

            1. 展平对象比当前解决方案更快。
            2. 对物体进行展平和取消处理与当前解决方案一样快或更快。
            3. 为了便于阅读,展平对象同时使用点表示法和括号表示法。
            4. <强>缺点

              1. 在大多数(但不是全部)情况下,取消对象的取消比当前解决方案慢。

              2. 当前JSFiddle demo将以下值作为输出:

                Nested : 132175 : 63
                Flattened : 132175 : 564
                Nested : 132175 : 54
                Flattened : 132175 : 508
                

                我更新的JSFiddle demo将以下值作为输出:

                Nested : 132175 : 59
                Flattened : 132175 : 514
                Nested : 132175 : 60
                Flattened : 132175 : 451
                

                我不确定这意味着什么,所以我会坚持使用jsPerf结果。毕竟jsPerf是一个性能基准测试工具。 JSFiddle不是。

答案 2 :(得分:10)

根据@ Bergi的代码,我制作了一个简单的网页来展平//不平整。

http://fiddle.jshell.net/blowsie/S2hsS/show/light/

enter image description here

&#13;
&#13;
JSON.flatten = function (data) {
    var result = {};

    function recurse(cur, prop) {
        if (Object(cur) !== cur) {
            result[prop] = cur;
        } else if (Array.isArray(cur)) {
            for (var i = 0, l = cur.length; i < l; i++)
            recurse(cur[i], prop + "[" + i + "]");
            if (l == 0) result[prop] = [];
        } else {
            var isEmpty = true;
            for (var p in cur) {
                isEmpty = false;
                recurse(cur[p], prop ? prop + "." + p : p);
            }
            if (isEmpty && prop) result[prop] = {};
        }
    }
    recurse(data, "");
    return result;
};
JSON.unflatten = function (data) {
    "use strict";
    if (Object(data) !== data || Array.isArray(data)) return data;
    var regex = /\.?([^.\[\]]+)|\[(\d+)\]/g,
        resultholder = {};
    for (var p in data) {
        var cur = resultholder,
            prop = "",
            m;
        while (m = regex.exec(p)) {
            cur = cur[prop] || (cur[prop] = (m[2] ? [] : {}));
            prop = m[2] || m[1];
        }
        cur[prop] = data[p];
    }
    return resultholder[""] || resultholder;
};


$("#process").click(function () {
    var flatten = $("#flatten").is(":checked");

    var result = flatten ? JSON.stringify(JSON.flatten(JSON.parse($("#input").val())), null, "\t") : JSON.stringify(JSON.unflatten(JSON.parse($("#input").val())), null, "\t")

    $("#output").val(result);
    $("#formatted").text(result);
});
&#13;
body {
    padding:20px;
}
&#13;
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<h1>JSON Flattener</h1>

<div class="form-group">
    <label>Mode:</label>
    <label class="radio-inline">
        <input id="flatten" name="mode" type="radio" value="flatten" checked="">Flatten</label>
    <label class="radio-inline">
        <input name="mode" type="radio" value="unflatten">Unflatten</label>
</div>
<div class="form-group">
    <label>Input:</label>
    <input class="form-control" type="text" name="" id="input">
</div>
<div class="form-group">
    <label>Output:</label>
    <textarea class="form-control" name="" id="output" cols="30" rows="5"></textarea>
</div>
<button id="process" class="btn btn-primary">Process</button>
<br/>
<br/>
<label>Formatted:</label>
<pre><code id="formatted"></code></pre>
&#13;
&#13;
&#13;

答案 3 :(得分:7)

3年后......

对于我自己的项目,我想在mongoDB dot notation中展平JSON对象并提出一个简单的解决方案:

/**
 * Recursively flattens a JSON object using dot notation.
 *
 * NOTE: input must be an object as described by JSON spec. Arbitrary
 * JS objects (e.g. {a: () => 42}) may result in unexpected output.
 * MOREOVER, it removes keys with empty objects/arrays as value (see
 * examples bellow).
 *
 * @example
 * // returns {a:1, 'b.0.c': 2, 'b.0.d.e': 3, 'b.1': 4}
 * flatten({a: 1, b: [{c: 2, d: {e: 3}}, 4]})
 * // returns {a:1, 'b.0.c': 2, 'b.0.d.e.0': true, 'b.0.d.e.1': false, 'b.0.d.e.2.f': 1}
 * flatten({a: 1, b: [{c: 2, d: {e: [true, false, {f: 1}]}}]})
 * // return {a: 1}
 * flatten({a: 1, b: [], c: {}})
 *
 * @param obj item to be flattened
 * @param {Array.string} [prefix=[]] chain of prefix joined with a dot and prepended to key
 * @param {Object} [current={}] result of flatten during the recursion
 *
 * @see https://docs.mongodb.com/manual/core/document/#dot-notation
 */
function flatten (obj, prefix, current) {
  prefix = prefix || []
  current = current || {}

  // Remember kids, null is also an object!
  if (typeof (obj) === 'object' && obj !== null) {
    Object.keys(obj).forEach(key => {
      this.flatten(obj[key], prefix.concat(key), current)
    })
  } else {
    current[prefix.join('.')] = obj
  }

  return current
}

功能和/或警告

  • 它只接受JSON对象。所以如果你传递像{a: () => {}}这样的东西,你可能得不到你想要的东西!
  • 删除空数组和对象。因此,此{a: {}, b: []}已展平为{}

答案 4 :(得分:6)

这是另一种比上述答案运行得慢(大约1000ms)的方法,但有一个有趣的想法: - )

它不是遍历每个属性链,而是选择最后一个属性,并使用查找表来存储中间结果。这个查找表将被迭代,直到没有剩下属性链,并且所有值都驻留在未经过连接的属性上。

JSON.unflatten = function(data) {
    "use strict";
    if (Object(data) !== data || Array.isArray(data))
        return data;
    var regex = /\.?([^.\[\]]+)$|\[(\d+)\]$/,
        props = Object.keys(data),
        result, p;
    while(p = props.shift()) {
        var m = regex.exec(p),
            target;
        if (m.index) {
            var rest = p.slice(0, m.index);
            if (!(rest in data)) {
                data[rest] = m[2] ? [] : {};
                props.push(rest);
            }
            target = data[rest];
        } else {
            target = result || (result = (m[2] ? [] : {}));
        }
        target[m[2] || m[1]] = data[p];
    }
    return result;
};

它目前使用表的data输入参数,并在其上放置许多属性 - 也应该是非破坏性版本。也许聪明的lastIndexOf用法比正则表达式更好(取决于正则表达式引擎)。

See it in action here

答案 5 :(得分:4)

ES6版本:

const flatten = (obj, path = '') => {        
    if (!(obj instanceof Object)) return {[path.replace(/\.$/g, '')]:obj};

    return Object.keys(obj).reduce((output, key) => {
        return obj instanceof Array ? 
             {...output, ...flatten(obj[key], path +  '[' + key + '].')}:
             {...output, ...flatten(obj[key], path + key + '.')};
    }, {});
}

示例:

console.log(flatten({a:[{b:["c","d"]}]}));
console.log(flatten([1,[2,[3,4],5],6]));

答案 6 :(得分:3)

您可以使用https://github.com/hughsk/flat

  

获取嵌套的Javascript对象并将其展平,或者用带分隔符的键取消对象。

doc

中的示例
var flatten = require('flat')

flatten({
    key1: {
        keyA: 'valueI'
    },
    key2: {
        keyB: 'valueII'
    },
    key3: { a: { b: { c: 2 } } }
})

// {
//   'key1.keyA': 'valueI',
//   'key2.keyB': 'valueII',
//   'key3.a.b.c': 2
// }


var unflatten = require('flat').unflatten

unflatten({
    'three.levels.deep': 42,
    'three.levels': {
        nested: true
    }
})

// {
//     three: {
//         levels: {
//             deep: 42,
//             nested: true
//         }
//     }
// }

答案 7 :(得分:2)

此代码以递归方式展平JSON对象。

我在代码中包含了我的计时机制,它给了我1ms,但我不确定这是否是最准确的。

            var new_json = [{
              "name": "fatima",
              "age": 25,
              "neighbour": {
                "name": "taqi",
                "location": "end of the street",
                "property": {
                  "built in": 1990,
                  "owned": false,
                  "years on market": [1990, 1998, 2002, 2013],
                  "year short listed": [], //means never
                }
              },
              "town": "Mountain View",
              "state": "CA"
            },
            {
              "name": "qianru",
              "age": 20,
              "neighbour": {
                "name": "joe",
                "location": "opposite to the park",
                "property": {
                  "built in": 2011,
                  "owned": true,
                  "years on market": [1996, 2011],
                  "year short listed": [], //means never
                }
              },
              "town": "Pittsburgh",
              "state": "PA"
            }]

            function flatten(json, flattened, str_key) {
                for (var key in json) {
                  if (json.hasOwnProperty(key)) {
                    if (json[key] instanceof Object && json[key] != "") {
                      flatten(json[key], flattened, str_key + "." + key);
                    } else {
                      flattened[str_key + "." + key] = json[key];
                    }
                  }
                }
            }

        var flattened = {};
        console.time('flatten'); 
        flatten(new_json, flattened, "");
        console.timeEnd('flatten');

        for (var key in flattened){
          console.log(key + ": " + flattened[key]);
        }

输出:

flatten: 1ms
.0.name: fatima
.0.age: 25
.0.neighbour.name: taqi
.0.neighbour.location: end of the street
.0.neighbour.property.built in: 1990
.0.neighbour.property.owned: false
.0.neighbour.property.years on market.0: 1990
.0.neighbour.property.years on market.1: 1998
.0.neighbour.property.years on market.2: 2002
.0.neighbour.property.years on market.3: 2013
.0.neighbour.property.year short listed: 
.0.town: Mountain View
.0.state: CA
.1.name: qianru
.1.age: 20
.1.neighbour.name: joe
.1.neighbour.location: opposite to the park
.1.neighbour.property.built in: 2011
.1.neighbour.property.owned: true
.1.neighbour.property.years on market.0: 1996
.1.neighbour.property.years on market.1: 2011
.1.neighbour.property.year short listed: 
.1.town: Pittsburgh
.1.state: PA

答案 8 :(得分:1)

Object.prototype.flatten = function (obj) {

    let ans = {};
    let anotherObj = { ...obj };
    function performFlatten(anotherObj) {

        Object.keys(anotherObj).forEach((key, idx) => {
            if (typeof anotherObj[key] !== 'object') {
                ans[key] = anotherObj[key];
                console.log('ans so far : ', ans);
            } else {
                console.log(key, { ...anotherObj[key] });
                performFlatten(anotherObj[key]);
            }
        })
    }

    performFlatten(anotherObj);

    return ans;
}

let ans = flatten(obj);
console.log(ans);

答案 9 :(得分:1)

这是我的。它在一个相当大的对象上在Google Apps脚本中以<2ms的速度运行。它使用破折号而不是分隔符的点,并且它不像询问者的问题那样处理数组,但这是我想要的用途。

function flatten (obj) {
  var newObj = {};
  for (var key in obj) {
    if (typeof obj[key] === 'object' && obj[key] !== null) {
      var temp = flatten(obj[key])
      for (var key2 in temp) {
        newObj[key+"-"+key2] = temp[key2];
      }
    } else {
      newObj[key] = obj[key];
    }
  }
  return newObj;
}

示例:

var test = {
  a: 1,
  b: 2,
  c: {
    c1: 3.1,
    c2: 3.2
  },
  d: 4,
  e: {
    e1: 5.1,
    e2: 5.2,
    e3: {
      e3a: 5.31,
      e3b: 5.32
    },
    e4: 5.4
  },
  f: 6
}

Logger.log("start");
Logger.log(JSON.stringify(flatten(test),null,2));
Logger.log("done");

示例输出:

[17-02-08 13:21:05:245 CST] start
[17-02-08 13:21:05:246 CST] {
  "a": 1,
  "b": 2,
  "c-c1": 3.1,
  "c-c2": 3.2,
  "d": 4,
  "e-e1": 5.1,
  "e-e2": 5.2,
  "e-e3-e3a": 5.31,
  "e-e3-e3b": 5.32,
  "e-e4": 5.4,
  "f": 6
}
[17-02-08 13:21:05:247 CST] done

答案 10 :(得分:1)

通过次要代码重构和在函数名称空间之外移动递归函数,我为所选答案添加了+/- 10-15%的效率。

请参阅我的问题:Are namespaced functions reevaluated on every call?了解为什么这会降低嵌套函数的速度。

function _flatten (target, obj, path) {
  var i, empty;
  if (obj.constructor === Object) {
    empty = true;
    for (i in obj) {
      empty = false;
      _flatten(target, obj[i], path ? path + '.' + i : i);
    }
    if (empty && path) {
      target[path] = {};
    }
  } 
  else if (obj.constructor === Array) {
    i = obj.length;
    if (i > 0) {
      while (i--) {
        _flatten(target, obj[i], path + '[' + i + ']');
      }
    } else {
      target[path] = [];
    }
  }
  else {
    target[path] = obj;
  }
}

function flatten (data) {
  var result = {};
  _flatten(result, data, null);
  return result;
}

请参阅benchmark

答案 11 :(得分:0)

我想添加一个新版本的flatten case(这是我需要的:)),根据我使用上面的jsFiddler的探测器,它比当前选择的稍快一些。 此外,我个人认为这个片段更具可读性,这对于多开发人员项目来说当然很重要。

function flattenObject(graph) {
    let result = {},
        item,
        key;

    function recurr(graph, path) {
        if (Array.isArray(graph)) {
            graph.forEach(function (itm, idx) {
                key = path + '[' + idx + ']';
                if (itm && typeof itm === 'object') {
                    recurr(itm, key);
                } else {
                    result[key] = itm;
                }
            });
        } else {
            Reflect.ownKeys(graph).forEach(function (p) {
                key = path + '.' + p;
                item = graph[p];
                if (item && typeof item === 'object') {
                    recurr(item, key);
                } else {
                    result[key] = item;
                }
            });
        }
    }
    recurr(graph, '');

    return result;
}

答案 12 :(得分:0)

使用此库:

npm install flat

用法(来自https://www.npmjs.com/package/flat):

扁平:

    var flatten = require('flat')


    flatten({
        key1: {
            keyA: 'valueI'
        },
        key2: {
            keyB: 'valueII'
        },
        key3: { a: { b: { c: 2 } } }
    })

    // {
    //   'key1.keyA': 'valueI',
    //   'key2.keyB': 'valueII',
    //   'key3.a.b.c': 2
    // }

展平:

var unflatten = require('flat').unflatten

unflatten({
    'three.levels.deep': 42,
    'three.levels': {
        nested: true
    }
})

// {
//     three: {
//         levels: {
//             deep: 42,
//             nested: true
//         }
//     }
// }

答案 13 :(得分:0)

这是我编写的一些代码,用于拼合正在使用的对象。它创建一个新类,该类接受每个嵌套字段并将其带入第一层。您可以通过记住键的原始位置来对其进行修改以使其变平。它还假定键即使在嵌套对象中也是唯一的。希望对您有所帮助。

class JSONFlattener {
    ojson = {}
    flattenedjson = {}

    constructor(original_json) {
        this.ojson = original_json
        this.flattenedjson = {}
        this.flatten()
    }

    flatten() {
        Object.keys(this.ojson).forEach(function(key){
            if (this.ojson[key] == null) {

            } else if (this.ojson[key].constructor == ({}).constructor) {
                this.combine(new JSONFlattener(this.ojson[key]).returnJSON())
            } else {
                this.flattenedjson[key] = this.ojson[key]
            }
        }, this)        
    }

    combine(new_json) {
        //assumes new_json is a flat array
        Object.keys(new_json).forEach(function(key){
            if (!this.flattenedjson.hasOwnProperty(key)) {
                this.flattenedjson[key] = new_json[key]
            } else {
                console.log(key+" is a duplicate key")
            }
        }, this)
    }

    returnJSON() {
        return this.flattenedjson
    }
}

console.log(new JSONFlattener(dad_dictionary).returnJSON())

例如,它进行转换

nested_json = {
    "a": {
        "b": {
            "c": {
                "d": {
                    "a": 0
                }
            }
        }
    },
    "z": {
        "b":1
    },
    "d": {
        "c": {
            "c": 2
        }
    }
}

进入

{ a: 0, b: 1, c: 2 }

答案 14 :(得分:0)

这是我在PowerShell中放在一起的扁平化递归解决方案:

#---helper function for ConvertTo-JhcUtilJsonTable
#
function getNodes {
    param (
        [Parameter(Mandatory)]
        [System.Object]
        $job,
        [Parameter(Mandatory)]
        [System.String]
        $path
    )

    $t = $job.GetType()
    $ct = 0
    $h = @{}

    if ($t.Name -eq 'PSCustomObject') {
        foreach ($m in Get-Member -InputObject $job -MemberType NoteProperty) {
            getNodes -job $job.($m.Name) -path ($path + '.' + $m.Name)
        }
        
    }
    elseif ($t.Name -eq 'Object[]') {
        foreach ($o in $job) {
            getNodes -job $o -path ($path + "[$ct]")
            $ct++
        }
    }
    else {
        $h[$path] = $job
        $h
    }
}


#---flattens a JSON document object into a key value table where keys are proper JSON paths corresponding to their value
#
function ConvertTo-JhcUtilJsonTable {
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [System.Object[]]
        $jsonObj
    )

    begin {
        $rootNode = 'root'    
    }
    
    process {
        foreach ($o in $jsonObj) {
            $table = getNodes -job $o -path $rootNode

            # $h = @{}
            $a = @()
            $pat = '^' + $rootNode
            
            foreach ($i in $table) {
                foreach ($k in $i.keys) {
                    # $h[$k -replace $pat, ''] = $i[$k]
                    $a += New-Object -TypeName psobject -Property @{'Key' = $($k -replace $pat, ''); 'Value' = $i[$k]}
                    # $h[$k -replace $pat, ''] = $i[$k]
                }
            }
            # $h
            $a
        }
    }

    end{}
}

示例:

'{"name": "John","Address": {"house": "1234", "Street": "Boogie Ave"}, "pets": [{"Type": "Dog", "Age": 4, "Toys": ["rubberBall", "rope"]},{"Type": "Cat", "Age": 7, "Toys": ["catNip"]}]}' | ConvertFrom-Json | ConvertTo-JhcUtilJsonTable
Key              Value
---              -----
.Address.house   1234
.Address.Street  Boogie Ave
.name            John
.pets[0].Age     4
.pets[0].Toys[0] rubberBall
.pets[0].Toys[1] rope
.pets[0].Type    Dog
.pets[1].Age     7
.pets[1].Toys[0] catNip
.pets[1].Type    Cat

答案 15 :(得分:0)

您可以试用jpflat软件包。

它可以展平,扩展,解决承诺,展平数组,具有可自定义的路径创建和可自定义的值序列化。

化简器和序列化器将整个路径作为部分数组接收,因此可以对路径进行更复杂的操作,而不用修改单个键或更改定界符。

Json路径是默认路径,因此为“ jp”平面。

https://www.npmjs.com/package/jpflat

let flatFoo = await require('jpflat').flatten(foo)

答案 16 :(得分:0)

我想要一种方法,以便能够轻松地将我的 json 数据转换为 csv 文件。 场景是:我从某个地方查询数据,然后收到一些模型的数组,例如银行提取物。 下面的这种方法用于解析这些条目中的每一个。

function jsonFlatter(data, previousKey, obj) {
    obj = obj || {}
    previousKey = previousKey || ""
    Object.keys(data).map(key => {
        let newKey = `${previousKey}${previousKey ? "_" : ""}${key}`
        let _value = data[key]
        let isArray = Array.isArray(_value)
        if (typeof _value !== "object" || isArray || _value == null) {
            if (isArray) {
                _value = JSON.stringify(_value)
            } else if (_value == null) {
                _value = "null"
            }
            obj[newKey] = _value
        } else if (typeof _value === "object") {
            if (!Object.keys(_value).length) {
                obj[newKey] = "null"
            } else {
                return jsonFlatter(_value, newKey, obj)
            }
        }
    })
    return obj
}

通过这种方式,我可以依赖对象模型的键和内部键的一致性,但数组只是字符串化,因为我不能依赖它们的一致性。此外,空对象成为字符串“null”,因为我仍然希望它的关键出现在最终结果中。

用法示例:

const test_data = {
    a: {
        aa: {
            aaa: 4354,
            aab: 654
        },
        ab: 123
    },
    b: 234,
    c: {},
    d: []
}

console.log('result', jsonFlatter(test_data)) 

#### output
{
  "a_aa_aaa": 4354,
  "a_aa_aab": 654,
  "a_ab": 123,
  "b": 234,
  "c": "null",
  "d": "[]"
}