将json扁平化为csv格式

时间:2012-07-04 16:11:23

标签: javascript arrays json csv hash

我正在尝试根据用户选择的字段将json值转换为flat 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,但我想保存根本身的详细信息..

如果我选择Time,csv输出应该是,

"test", "news", "propertyFile 9","null", "50", "Events": "Time", "Dec 9", "2012"

是否有可能使json变平..我将添加json小提琴链接以显示我用这个东西到达的地方.. http://jsfiddle.net/JHCwM/

6 个答案:

答案 0 :(得分:2)

您的data值不是JSON(字符串) - 它是一个对象。有很多方法可以“压扁”这个对象,可能这个小功能可能会有所帮助:

var recMap = function(obj) {
  return $.map(obj, function(val) { 
    return typeof val !== 'object' ? val : recMap(val); 
  });
}

here是如何使用它的。 )

答案 1 :(得分:1)

以下是将对象展平为键/值对的另一种方法,其中键是属性的完整路径。



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




答案 2 :(得分:1)

有一个 npm lib 专门为此提供了很多选项:https://mircozeiss.com/json2csv/

# Global install so it can be called from anywhere
$ npm install -g json2csv

## Generate CSV file
$ json2csv -i data.json -o out.csv --flatten-objects

答案 3 :(得分:0)

答案 4 :(得分:0)

尝试以下方法:

http://codebeautify.org/view/jsonviewer

使用导出到CSV按钮

答案 5 :(得分:0)

检查出来以展平Json

// Convert Nested Json to Flat Json
// Check the final json in firebug console.
var fullData = {"data":[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42,"Children":[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42,"Children":[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42,"Children":[]}]},{"Vehicle":"Honda CBR","Date":"30, Jul 2013 12:00 AM","Location":"Military Road,  West Bengal 734013,  India","Speed":0,"Children":[]}]},{"Vehicle":"Honda CBR","Date":"30, Jul 2013 12:00 AM","Location":"Military Road,  West Bengal 734013,  India","Speed":0,"Children":[]},{"Vehicle":"Supra","Date":"30, Jul 2013 07:53 AM","Location":"Sec-45, St. Angel's School, Gurgaon, Haryana, India","Speed":58,"Children":[]},{"Vehicle":"Land Cruiser","Date":"30, Jul 2013 09:35 AM","Location":"DLF Phase I, Marble Market, Gurgaon, Haryana, India","Speed":83,"Children":[]},{"Vehicle":"Suzuki Swift","Date":"30, Jul 2013 12:02 AM","Location":"Behind Central Bank RO, Ram Krishna Rd by-lane, Siliguri, West Bengal, India","Speed":0,"Children":[]},{"Vehicle":"Honda Civic","Date":"30, Jul 2013 12:00 AM","Location":"Behind Central Bank RO, Ram Krishna Rd by-lane, Siliguri, West Bengal, India","Speed":0,"Children":[]},{"Vehicle":"Honda Accord","Date":"30, Jul 2013 11:05 AM","Location":"DLF Phase IV, Super Mart 1, Gurgaon, Haryana, India","Speed":71,"Children":[]}]}
var finalData = [];
loopJson(fullData.data);
function loopJson(data) {
    $.each(data, function(i, e) {
        if (e.Children.length>0) {
            var ccd = e.Children;
            delete e.Children;
            finalData.push(e);
            loopJson(ccd);
        } else {
            delete e.Children;
            finalData.push(e);
        }
    });
}
console.log(finalData);

这是Js小提琴链接http://jsfiddle.net/2nwm43yc/