本文介绍了最快的方式扁平化/非扁平化嵌套的JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我把一些code一起扁平化和未压扁复杂/嵌套的JSON对象。它的工作原理,但它是一个有点慢(触发'长剧本警告)。

I threw some code together to flatten and un-flatten complex/nested JSON objects. It works, but it's a bit slow (triggers the 'long script' warning).

有关平整名字我想要的。作为分隔符和[索引]数组。

For the flattened names I want "." as the delimiter and [INDEX] for arrays.

例如:

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对象
  • 将其压平
  • 在翻阅它,并可能修改它,而扁平化
  • Unflatten它回到它原来的嵌套形式被运走

我想更快code:对于澄清,code,它完成的jsfiddle基准(的http://的jsfiddle .NET / WSzec / )显著快(〜20%+将是不错)在IE 9 +,24 + FF和Chrome 29 +。

I would like faster code: For clarification, code that completes the JSFiddle benchmark (http://jsfiddle.net/WSzec/) significantly faster (~20%+ would be nice) in IE 9+, FF 24+, and Chrome 29+.

下面是相应的JavaScript code:当前最快: http://jsfiddle.net/WSzec/6/

Here's the relevant JavaScript code: Current Fastest: 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为20%左右在FF,但速度慢20%,快于Chrome浏览器;所以我会坚持使用正则表达式,因为它更简单(这里是我尝试使用的indexOf来代替正则表达式 http://jsfiddle.net/WSzec / 2 / )。

EDIT 1 Modified the above to @Bergi 's implementation which is currently the fastest. As an aside, using ".indexOf" instead of "regex.exec" is around 20% faster in FF but 20% slower in Chrome; so I'll stick with the regex since it's simpler (here's my attempt at using indexOf to replace the regex http://jsfiddle.net/WSzec/2/).

编辑2 大厦@Bergi的想法我要创建一个更快的非正则表达式版本管理(3倍快于FF和〜10%,在Chrome更快)。 http://jsfiddle.net/WSzec/6/ 在此(目前)实现的键名的规则是简单,钥匙无法启动与一个整数或包含句点。

EDIT 2 Building on @Bergi 's idea I managed to created a faster non-regex version (3x faster in FF and ~10% faster in Chrome). http://jsfiddle.net/WSzec/6/ In the this (the current) implementation the rules for key names are simply, keys cannot start with an integer or contain a period.

例如:

  • {富:{吧:[0]}} => {foo.bar.0:0}

修改3 添加@AaditMShah的内联路径分析方法(而不是String.split)有助于提高unflatten性能。我很高兴与达到整体性能的提升。

EDIT 3 Adding @AaditMShah 's inline path parsing approach (rather than String.split) helped to improve the unflatten performance. I'm very happy with the overall performance improvement reached.

最新的jsfiddle和jsperf:

The latest jsfiddle and jsperf:

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

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

推荐答案

下面是我的短得多的实现:

Here's my much shorter implementation:

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;
};

JSON.flatten 并没有太大的改变(我不知道你是否真的需要那些的isEmpty 例):

JSON.flatten hasn't much changed (and I'm not sure whether you really need those isEmpty cases):

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;
}

他们一起运行标杆有关时间的一半(歌剧12.16:〜900毫秒,而不是〜1900ms, Chrome浏览器29:〜800毫秒,而不是〜1600ms之间)

Together, they run your benchmark in about the half of the time (Opera 12.16: ~900ms instead of ~ 1900ms, Chrome 29: ~800ms instead of ~1600ms).

这篇关于最快的方式扁平化/非扁平化嵌套的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 05:54