我正在尝试根据用户选择的字段将 json 值转换为平面 csv。我的 json 看起来像
var data = {
"_index": "test",
"_type": "news",
"_source": {
"partnerName": "propertyFile 9",
"relatedSources": "null",
"entityCount": "50",
"Categories": {
"Types": {
"Events": [{
"count": 1,
"term": "Time",
"Time": [{
"term": "Dec 9",
"Dec_9": [{
"count": 1,
"term": "2012"
}]
}]
}, {
"count": 4,
"term": "News",
"News": [{
"term": "Germany",
"Germany": [{
"count": 1,
"term": "Election"
}],
"currency": "Euro (EUR)"
}, {
"term": "Egypt",
"Egypt": [{
"count": 1,
"term": "Revolution"
}]
}]
}]
}
}
}};
我能够收集所有出现的值并将其存储为 csv,但我想从根本身保存详细信息..
如果我选择时间,csv 输出应该如下所示,
"test", "news", "propertyFile 9","null", "50", "Events": "Time", "Dec 9", "2012"
是否有可能展平 json.. 我将添加 json fiddle 链接以显示我用这个东西到达的位置.. http://jsfiddle.net/JHCwM/
最佳答案
这是将对象扁平化为键/值对的另一种方法,其中键是属性的完整路径。
let data = {
pc: "Future Crew",
retro: {
c64: "Censor Design",
amiga: "Kefrens"
}
};
let flatten = (obj, path = []) => {
return Object.keys(obj).reduce((result, prop) => {
if (typeof obj[prop] !== "object") {
result[path.concat(prop).join(".")] = obj[prop];
return result;
}
return Object.assign(result, flatten(obj[prop], path.concat(prop), result));
}, {});
}
console.log(
flatten(data)
);
关于javascript - 将 json 扁平化为 csv 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11332530/