Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

javascript - convert json to csv format

I try to use as input a file in json format. Here is a snippet of example data.

[
{
id: 1671349531,
name: "A Wild Restaurant Expansion",
blurb: "We are looking to expand from our current location to a new and better facility. One that will be available for our our followers!",
goal: 17000,
pledged: 0,
state: "live",
slug: "a-wild-restaurant-expansion",
disable_communication: false,
country: "US",
currency: "USD",
currency_symbol: "$",
currency_trailing_code: true,
deadline: 1425185940,
state_changed_at: 1422373209,
created_at: 1422141288,
launched_at: 1422373209,
backers_count: 0,
photo: {
full: "https://s3.amazonaws.com/ksr/projects/1619167/photo-full.jpg?1422144440",
ed: "https://s3.amazonaws.com/ksr/projects/1619167/photo-ed.jpg?1422144440",
med: "https://s3.amazonaws.com/ksr/projects/1619167/photo-med.jpg?1422144440",
little: "https://s3.amazonaws.com/ksr/projects/1619167/photo-little.jpg?1422144440",
small: "https://s3.amazonaws.com/ksr/projects/1619167/photo-small.jpg?1422144440",
thumb: "https://s3.amazonaws.com/ksr/projects/1619167/photo-thumb.jpg?1422144440",
1024x768: "https://s3.amazonaws.com/ksr/projects/1619167/photo-1024x768.jpg?1422144440",
1536x1152: "https://s3.amazonaws.com/ksr/projects/1619167/photo-1536x1152.jpg?1422144440"
},
creator: {
id: 602131664,
name: "Chef James Nelson",
avatar: {
thumb: "https://s3.amazonaws.com/ksr/avatars/13830182/logo3.thumb.jpg?1422143536",
small: "https://s3.amazonaws.com/ksr/avatars/13830182/logo3.small.jpg?1422143536",
medium: "https://s3.amazonaws.com/ksr/avatars/13830182/logo3.medium.jpg?1422143536"
},
urls: {
web: {
user: "https://www.kickstarter.com/profile/602131664"
},
api: {
user: "https://api.kickstarter.com/v1/users/602131664?signature=1422460143.21cd79c238aeae43e8a4311c18bf8e8cd2c3a39a"
}
}
},
location: {
id: 2433186,
name: "Kissimmee",
slug: "kissimmee-fl",
short_name: "Kissimmee, FL",
displayable_name: "Kissimmee, FL",
country: "US",
state: "FL",
type: "Town",
is_root: false,
urls: {
web: {
discover: "https://www.kickstarter.com/discover/places/kissimmee-fl",
location: "https://www.kickstarter.com/locations/kissimmee-fl"
},
api: {
nearby_projects: "https://api.kickstarter.com/v1/discover?signature=1422447847.04d19a9efbe31a0d300969276d5d6f5ffa88a776&woe_id=2433186"
}
}
},
category: {
id: 312,
name: "Restaurants",
slug: "food/restaurants",
position: 9,
parent_id: 10,
urls: {
web: {
discover: "http://www.kickstarter.com/discover/categories/food/restaurants"
}
}
},
urls: {
web: {
project: "https://www.kickstarter.com/projects/602131664/a-wild-restaurant-expansion?ref=newest",
rewards: "https://www.kickstarter.com/projects/602131664/a-wild-restaurant-expansion/rewards"
}
}
},
{
id: 267033207,
name: "The Razors Edge ~ (based on the book Giggling in Fairmont).",
blurb: "An indie film to follow up on the recently published book. In it's first few weeks of release it has taken a strong grip on the world.",
goal: 5000,
pledged: 0,
state: "live",
slug: "the-razors-edge-based-on-the-book-giggling-in-fair",
disable_communication: false,
country: "US",
currency: "USD",
currency_symbol: "$",
currency_trailing_code: true,
deadline: 1424964564,
state_changed_at: 1422372564,
created_at: 1421465861,
launched_at: 1422372564,
backers_count: 0,
photo: {
full: "https://s3.amazonaws.com/ksr/projects/1599522/photo-full.jpg?1421465884",
ed: "https://s3.amazonaws.com/ksr/projects/1599522/photo-ed.jpg?1421465884",
med: "https://s3.amazonaws.com/ksr/projects/1599522/photo-med.jpg?1421465884",
little: "https://s3.amazonaws.com/ksr/projects/1599522/photo-little.jpg?1421465884",
small: "https://s3.amazonaws.com/ksr/projects/1599522/photo-small.jpg?1421465884",
thumb: "https://s3.amazonaws.com/ksr/projects/1599522/photo-thumb.jpg?1421465884",
1024x768: "https://s3.amazonaws.com/ksr/projects/1599522/photo-1024x768.jpg?1421465884",
1536x1152: "https://s3.amazonaws.com/ksr/projects/1599522/photo-1536x1152.jpg?1421465884"
},
creator: {
id: 198971258,
name: "Jesse Gerken",
avatar: {
thumb: "https://s3.amazonaws.com/ksr/avatars/12370207/author_pic.thumb.jpg?1411309933",
small: "https://s3.amazonaws.com/ksr/avatars/12370207/author_pic.small.jpg?1411309933",
medium: "https://s3.amazonaws.com/ksr/avatars/12370207/author_pic.medium.jpg?1411309933"
},
urls: {
web: {
user: "https://www.kickstarter.com/profile/198971258"
},
api: {
user: "https://api.kickstarter.com/v1/users/198971258?signature=1422460143.dd7e5606db2806a10e516e1def16575c3aae41e1"
}
}
},
location: {
id: 2401584,
name: "Fairmont",
slug: "fairmont-wv",
short_name: "Fairmont, WV",
displayable_name: "Fairmont, WV",
country: "US",
state: "WV",
type: "Town",
is_root: false,
urls: {
web: {
discover: "https://www.kickstarter.com/discover/places/fairmont-wv",
location: "https://www.kickstarter.com/locations/fairmont-wv"
},
api: {
nearby_projects: "https://api.kickstarter.com/v1/discover?signature=1422448035.58aff9025d72453411d574df4707a417d4b7b970&woe_id=2401584"
}
}
},
category: {
id: 297,
name: "Horror",
slug: "film & video/horror",
position: 10,
parent_id: 11,
urls: {
web: {
discover: "http://www.kickstarter.com/discover/categories/film%20&%20video/horror"
}
}
},
urls: {
web: {
project: "https://www.kickstarter.com/projects/198971258/the-razors-edge-based-on-the-book-giggling-in-fair?ref=newest",
rewards: "https://www.kickstarter.com/projects/198971258/the-razors-edge-based-on-the-book-giggling-in-fair/rewards"
}
}
},
{
id: 1791731386,
name: "PulseAuction",
blurb: "Seeking promotional funding for PulseAuction.com - a PATENTED online auction site. We've banished Per-Bid Fees! Join The Revolution.",
goal: 7000,
pledged: 0,
state: "live",
slug: "pulseauction",
disable_communication: false,
country: "US",
currency: "USD",
currency_symbol: "$",
currency_trailing_code: true,
deadline: 1424964553,
state_changed_at: 1422372553,
created_at: 1419635170,
launched_at: 1422372553,
backers_count: 0,
photo: {
full: "https://s3.amazonaws.com/ksr/projects/1559949/photo-full.jpg?1421250474",
ed: "https://s3.amazonaws.com/ksr/projects/1559949/photo-ed.jpg?1421250474",
med: "https://s3.amazonaws.com/ksr/projects/1559949/photo-med.jpg?1421250474",
little: "https://s3.amazonaws.com/ksr/projects/1559949/photo-little.jpg?1421250474",
small: "https://s3.amazonaws.com/ksr/projects/1559949/photo-small.jpg?1421250474",
thumb: "https://s3.amazonaws.com/ksr/projects/1559949/photo-thumb.jpg?1421250474",
1024x768: "https://s3.amazonaws.com/ksr/projects/1559949/photo-1024x768.jpg?1421250474",
1536x1152: "https://s3.amazonaws.com/ksr/projects/1559949/photo-1536x1152.jpg?1421250474"
},
creator: {
id: 835111372,
name: "WW Pulse Inc. dba PulseAuction.com",
avatar: {
thumb: "https://s3.amazonaws.com/ksr/avatars/13524481/rick_head_shot_Cleaned.thumb.jpg?1420034475",
small: "https://s3.amazonaws.com/ksr/avatars/13524481/rick_head_shot_Cleaned.small.jpg?1420034475",
medium: "https://s3.amazonaws.com/ksr/avatars/13524481/rick_head_shot_Cleaned.medium.jpg?1420034475"
},
urls: {
web: {
user: "https://www.kickstarter.com/profile/835111372"
},
api: {
user: "https://api.kickstarter.com/v1/users/835111372?signature=1422460143.e75af1301e433dc803f3f929249d0c45ce3eaebd"
}
}
},
location: {
id: 23689683,
name: "South Florida",
slug: "south-florida-fl",
short_name: "South Florida, FL",
displayable_name: "South Florida, FL",
country: "US",
state: "FL",
type: "Town",
is_root: false,
urls: {
web: {
discover: "https://www.kickstarter.com/discover/places/south-florida-fl",
location: "https://www.kickstarter.com/locations/south-florida-fl"
},
api: {
nearby_projects: "https://api.kickstarter.com/v1/discover?signature=1422447780.143e234a4af62e7d8366fad3b204044920bcbc66&woe_id=23689683"
}
}
},
category: {
id: 342,
name: "Web",
slug: "technology/web",
position: 15,
parent_id: 16,
urls: {
web: {
discover: "http://www.kickstarter.com/discover/categories/technology/web"
}
}
},
urls: {
web: {
project: "https://www.kickstarter.com/projects/835111372/pulseauction?ref=newest",
rewards: "https://www.kickstarter.com/projects/835111372/pulseauction/rewards"
}
}
}

Could be possible in r to make a csv using this complex json format in order to handle the data smoother?

For example there are these basic catagories: basic information photo creator location category urls

Could be possible to make a csv file with categories of subcategories like basic_information.id, creator.id etc?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Another implementation without json-2-csv that can handle complex data:

    // Some complex demo data
    var data = [
        {
            "id": "111",
            "name": "Johny Smith",
            "age": "23",
            "dates": [
                {
                    "birthday": "01.01.1990",
                    "nameday": "02.02",
                    "phone": {
                        "home": "02123123123123",
                        "mobile": "07124123123",
                    }
                }
            ]
        },
        {
            "id": "222",
            "name": "Jane Alex",
            "age": "43",
            "dates": [
                {
                    "birthday": "06.06.1997",
                    "nameday": "03.03",
                    "phone": {
                        "home": "029999999999999",
                        "mobile": "0788888888",
                    }
                }
            ]
        }
    ];

    // Converted string ready to be downloaded as csv
    var converted = toCsv(data);

    // This is used to automatically generate and download the  .CSV file
    var element = document.createElement('a');
    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(converted));
    element.setAttribute('download', "Output.csv");
    element.style.display = 'none';
    document.body.appendChild(element);
    element.click();
    document.body.removeChild(element);


    //////////////////////////////////// THE MAGIC  -> ////////////////////////////////////

    function toCsv(arr) {
        arr = pivot(arr);
        return arr.map(function (row) {
            return row.map(function (val) {
                return isNaN(val) ? JSON.stringify(val) : +val;
            }).join(',');
        }).join('
');
    }

    function toConsumableArray(arr) {
        if (Array.isArray(arr)) {
            for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
                arr2[i] = arr[i];
            }
            return arr2;
        } else {
            return Array.from(arr);
        }
    }

    function pivot(arr) {
        var mp = new Map();

        function setValue(a, path, val) {
            if (Object(val) !== val) {
                // primitive value
                var pathStr = path.join('.');
                var i = (mp.has(pathStr) ? mp : mp.set(pathStr, mp.size)).get(pathStr);
                a[i] = val;
            } else {
                for (var key in val) {
                    setValue(a, key == '0' ? path : path.concat(key), val[key]);
                }
            }
            return a;
        }

        var result = arr.map(function (obj) {
            return setValue([], [], obj);
        });
        let outcome = ([[].concat(toConsumableArray(mp.keys()))].concat(toConsumableArray(result)));

        return outcome;
    }

See JS Fiddle -> https://jsfiddle.net/gbktnd1j/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...