flattening json to csv format

2019-07-13 11:04发布

问题:

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

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..

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

"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/

回答1:

Your data value 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:

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

And here's how it can be used. )



回答2:

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



回答3:

Try looking here:

http://www.zachhunter.com/2011/06/json-to-csv/

and here:

How to convert JSON to CSV format and store in a variable



回答4:

Try the following :

http://codebeautify.org/view/jsonviewer

Use Export to CSV button



回答5:

Check this out to flatten the 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/