중첩 된 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://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 개체.
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));
성능 :
- Opera의 현재 솔루션보다 빠릅니다. 현재 솔루션은 Opera에서 26 % 느립니다.
- Firefox의 현재 솔루션보다 빠릅니다. 현재 솔루션은 Firefox에서 9 % 느립니다.
- Chrome의 현재 솔루션보다 빠릅니다. 현재 솔루션은 Chrome에서 29 % 느립니다.
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[""];
}
성능 :
- Opera의 현재 솔루션보다 빠릅니다. 현재 솔루션은 Opera에서 5 % 느립니다.
- Firefox의 현재 솔루션보다 느립니다. 내 솔루션은 Firefox에서 26 % 느립니다.
- Chrome의 현재 솔루션보다 느립니다. 내 솔루션은 Chrome에서 6 % 느립니다.
전반적으로 내 솔루션은 현재 솔루션과 동일하거나 더 나은 성능을 발휘합니다.
성능 :
- Opera의 현재 솔루션보다 빠릅니다. 현재 솔루션은 Opera에서 21 % 느립니다.
- Firefox의 현재 솔루션만큼 빠릅니다.
- Firefox의 현재 솔루션보다 빠릅니다. 현재 솔루션은 Chrome에서 20 % 느립니다.
출력 형식 :
병합 된 객체는 객체 속성에 도트 표기법을 사용하고 배열 인덱스에 대해서는 괄호 표기법을 사용합니다.
{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}
내 의견으로는이 형식은 점 표기법을 사용하는 것보다 낫습니다.
{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}
장점 :
- 객체를 평평하게하는 것이 현재 솔루션보다 빠릅니다.
- 객체를 평평하게하고 평평하게하는 것은 현재 솔루션보다 빠르거나 빠릅니다.
- 전개 된 객체는 가독성을 위해 점 표기법과 대괄호 표기법을 모두 사용합니다.
단점 :
- 대부분의 경우 (전부는 아님) 개체의 전개를 풀면 현재 솔루션보다 느려집니다.
현재 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은 그렇지 않습니다.
@ Bergi의 코드를 기반으로 // 평평하지 않은 간단한 웹 페이지를 만들었습니다.
http://fiddle.jshell.net/blowsie/S2hsS/show/light/

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);
});
body {
padding:20px;
}
<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>
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
마이너 코드 리팩토링과 재귀 함수를 함수 네임 스페이스 외부로 이동하여 선택한 답변에 +/- 10-15 %의 효율성을 추가했습니다.
내 질문을 참조하십시오 : 네임 스페이스 함수는 모든 호출에서 재평가됩니까? 왜 이것이 중첩 함수를 느리게합니까?
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;
}
기준을 참조하십시오 .
내 꺼야 크기 조정이 가능한 객체의 Google Apps Script에서 2ms 미만으로 실행됩니다. 구분 기호로 점 대신 대시를 사용하며 asker의 질문과 같이 특별히 배열을 처리하지 않지만 이것이 내가 사용하기를 원하는 것입니다.
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
위의 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;
}
이 라이브러리를 사용하십시오.
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
// }
// }
// }
참고 URL : https://stackoverflow.com/questions/19098797/fastest-way-to-flatten-un-flatten-nested-json-objects
'Programming' 카테고리의 다른 글
| HTML5 캔버스 요소에 텍스트를 작성하려면 어떻게해야합니까? (0) | 2020.06.18 |
|---|---|
| 골란 난수 생성기 (0) | 2020.06.18 |
| Emacs에서 여러 쉘을 실행하는 방법 (0) | 2020.06.18 |
| Django Admin에서 동일한 모델에 대한 여러 ModelAdmins / views (0) | 2020.06.18 |
| MySQL과 SQL Server의 차이점 (0) | 2020.06.18 |