将 json 转换为 csv 格式

convert json to csv format

我尝试使用 json 格式的文件作为输入。这是示例数据的片段。

[
{
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"
}
}
}

是否可以在 r 中使用这种复杂的 json 格式制作 csv 以便更顺畅地处理数据?

例如有这些基本类别: 基本信息 照片 创造者 地点 类别 网址

是否可以制作一个包含 basic_information.id、creator.id 等子类别类别的 csv 文件?

我在研究您的答案时在评论中发布了几个 link,但现在我非常确信 this is the way to do it

安装节点包,然后将以下内容与您自己的 json 字符串一起使用(我刚刚从上面的 link 中提取出来。):

var converter = require('json-2-csv');

var documents = [
    {
        Make: 'Nissan',
        Model: 'Murano',
        Year: '2013',
        Specifications: {
            Mileage: '7106',
            Trim: 'S AWD'
        }
    },
    {
        Make: 'BMW',
        Model: 'X5',
        Year: '2014',
        Specifications: {
            Mileage: '3287',
            Trim: 'M'
        }
    }
];

var json2csvCallback = function (err, csv) {
    if (err) throw err;
    console.log(csv);
};

converter.json2csv(documents, json2csvCallback);

这将 return:

Make,Model,Year,Specifications.Mileage,Specifications.Trim
Nissan,Murano,2013,7106,S AWD
BMW,X5,2014,3287,M

另一种没有 json-2-csv 的可以处理复杂数据的实现:

    // 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('\n');
    }

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

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