javascript - 将 json 扁平化为 csv 格式

标签 javascript arrays json csv hash

我正在尝试根据用户选择的字段将 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/

相关文章:

Javascript - 单击 svg 形状时调用函数。

javascript - 为什么 jquery sortable 不适用于 Canvas ?

javascript - 更新未定义?

JavaScript native 方法静默失败而不是抛出错误

java - 关于使用字符串数组形式的值查询 Java Map。

c++ - 在类中为静态无符号字符传递和分配值

java - httpUrlConnextion.getContentLength 返回不正确的值

c++ - 在 C++ 中对数组进行二进制搜索

python - 如何在 python 中过滤和打印特定的 json 字典

ios - 类型[字符串: String] does not conform to protocol 'AnyObject'