중첩 된 JSON 객체를 평면화 / 비편 성화하는 가장 빠른 방법

복잡한 / 중첩 된 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 29 에서 JSFiddle 벤치 마크 ( http://jsfiddle.net/WSzec/ )를 훨씬 더 빠르게 완료하는 코드 (~ 20 % 이상이 좋을 것입니다) +.

관련 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 구현으로 수정했습니다. 또한 “regex.exec”대신 “.indexOf”를 사용하면 FF는 약 20 % 빠르지 만 Chrome에서는 20 % 느립니다. 그래서 정규식이 더 간단하기 때문에 정규식을 고수 할 것입니다 (여기서 정규식 http://jsfiddle.net/WSzec/2/ 을 대체하기 위해 indexOf를 사용하려는 시도가 있습니다 ).

편집 2 @ Bergi의 아이디어를 바탕으로 더 빠른 비정규 버전을 만들었습니다 (FF에서 3 배 빠르며 Chrome에서는 ~ 10 % 빠름). http://jsfiddle.net/WSzec/6/ this (현재) 구현에서 키 이름에 대한 규칙은 간단합니다. 키는 정수로 시작하거나 마침표를 포함 할 수 없습니다.

예:

  • { “foo”: { “bar”: [0]}} => { “foo.bar.0”: 0}

편집 3 @AaditMShah의 인라인 경로 구문 분석 방식 (String.split 대신)을 추가하면 성능이 향상되지 않았습니다. 전반적인 성능 향상에 매우 만족합니다.

최신 jsfiddle 및 jsperf :

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

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



답변

여기 훨씬 짧은 구현이 있습니다.

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

함께, 그들은 절반의 시간 안에 벤치 마크실행합니다 (Opera 12.16 : ~ 1900ms 대신 ~ 900ms, Chrome 29 : ~ 1600ms 대신 ~ 800ms).

참고 : 여기에 언급 된이 솔루션과 대부분의 다른 솔루션은 속도에 중점을두고 프로토 타입 오염에 취약하며 신뢰할 수없는 물체에는 사용하지 않습니다.


답변

나는 두 개의 기능을 작성 flatten하고 unflattenJSON 개체.


JSON 객체를 평평하게 :

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 % 느립니다.

JSON 객체를 풀다 :

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 % 느립니다.

JSON 객체를 평면화 및 평면화 해제 :

전반적으로 내 솔루션은 현재 솔루션과 동일하거나 더 잘 수행됩니다.

성능 :

  1. Opera의 현재 솔루션보다 빠릅니다. 현재 솔루션은 Opera에서 21 % 느립니다.
  2. Firefox의 현재 솔루션만큼 빠릅니다.
  3. Firefox의 현재 솔루션보다 빠릅니다. 현재 솔루션은 Chrome에서 20 % 느립니다.

출력 형식 :

병합 된 객체는 객체 속성에 도트 표기법을 사용하고 배열 인덱스에 대해서는 괄호 표기법을 사용합니다.

  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}

내 의견으로는이 형식은 점 표기법을 사용하는 것보다 낫습니다.

  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}

장점 :

  1. 객체를 평평하게하는 것이 현재 솔루션보다 빠릅니다.
  2. 객체를 평평하게하고 평평하게하는 것은 현재 솔루션보다 빠르거나 빠릅니다.
  3. 전개 된 객체는 가독성을 위해 점 표기법과 대괄호 표기법을 모두 사용합니다.

단점 :

  1. 대부분의 경우 (전부는 아님) 개체의 전개를 풀면 현재 솔루션보다 느려집니다.

현재 JSFiddle 데모 는 다음 값을 출력으로 제공했습니다.

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

업데이트 된 JSFiddle 데모 는 다음 값을 출력으로 제공했습니다.

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

그게 무슨 뜻인지 잘 모르겠으므로 jsPerf 결과를 고수하겠습니다. 모든 jsPerf는 성능 벤치마킹 유틸리티입니다. JSFiddle은 그렇지 않습니다.


답변

3 년 반 후에 …

내 자신의 프로젝트를 위해 mongoDB 도트 표기법으로 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: []}평면화됩니다 {}.

답변

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]));

답변

위의 답변보다 느리게 (약 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사용법은 정규식보다 성능이 좋을 수도 있습니다 (정규식 엔진에 따라 다름).

여기에서 실제로 확인하십시오 .


답변

https://github.com/hughsk/flat 을 사용할 수 있습니다

중첩 된 Javascript 객체를 가져 와서 평평하게하거나 구분 된 키로 객체를 평평하게합니다.

문서의 예

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

답변

이 코드는 재귀 적으로 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