javascript 将 json 扁平化为 csv 格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11332530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:48:53  来源:igfitidea点击:

flattening json to csv format

javascriptarraysjsoncsvhash

提问by user1371896

i am trying to convert a json value to a flat csv based on the field that is selected by user . My json looks like

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

Ive been able to collect the values of all occurences and store it as a csv, but I want to save the details from the root itself..

我已经能够收集所有出现的值并将其存储为 csv,但我想从根本身保存详细信息..

If I select Time, the csv output should look like,

如果我选择时间,csv 输出应该是这样的,

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

Is it possible to flatten the json.. I will add the json fiddle link to show where Ive reached with this thing.. http://jsfiddle.net/JHCwM/

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

回答by raina77ow

Your datavalue is not a JSON (string) - it's an object. There are many ways to 'flatten' this object, may be this little function might be helpful:

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

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

And here's how it can be used. )

这里的它如何被使用。)

回答by stpe

Here is an alternative way to flatten an object into key/value pairs, where the key is the complete path of the property.

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

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

回答by Mohamed Zaghloul

Try the following :

尝试以下操作:

http://codebeautify.org/view/jsonviewer

http://codebeautify.org/view/jsonviewer

Use Export to CSV button

使用导出到 CSV 按钮

回答by ronnjoe

Check this out to flatten the Json

检查这个以压平 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);

Here is Js fiddle link http://jsfiddle.net/2nwm43yc/

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