将JSON对象转换为特定的CSV格式

时间:2018-08-27 05:13:56

标签: json node.js excel csv npm

我要转换

model = Sequential()
model.add(Reshape((-1, 1)
model.add(LSTM(44, input_shape=(6900, 44), ))
model.add(Dense(1))
model.compile(loss='mape', optimizer='adam', metrics=['mse', 'mae', 'mape'])
model.fit(X_train, y_train, epochs=100, batch_size=10, verbose=1)

对此

{
    "Name A":{
        "Name B":{
            "Name C":"Value C",
            "Name D":"Value D",
            "Name E":"Value E"
        }
    }
}

在excel中打开时看起来像这样
enter image description here

我试图通过运行一个小的脚本来实现这一目标,但是在此之前,我想检查是否有任何节点软件包或工具可以轻松实现这一目标。有任何线索吗?

2 个答案:

答案 0 :(得分:1)

也许可以尝试使用此npm模块csvjson
链接在这里:-https://www.npmjs.com/package/csvjson

答案 1 :(得分:0)

我通过编写自己的脚本解决了这个问题。我不得不根据数据格式进行一些微调以适应我的需要。这不是最优雅的解决方案。这是我工作的快速肮脏解决方案。如果有人想尝试编写自己的脚本以将JSON转换为CSV仍然是一个很好的参考

var fs = require('fs');

var file = 'templateEn.json';

var content = fs.readFileSync(file, { encoding: 'binary' });

var obj = JSON.parse(content);

var jsonString = ""

var lineEnd   = "\r\n";

var firstLevelKeys = Object.keys(obj);
jsonString      += firstLevelKeys[0] + ",,,,," + lineEnd;
var secondLevelKeys  = Object.keys(obj["en"]);
secondLevelKeys.forEach(key => {
    jsonString     += ',' + key +',,,,'+ lineEnd
    var thirdLevelKeys  = Object.keys(obj["en"][key]);
    thirdLevelKeys.forEach(key2=>{
        if (typeof obj["en"][key][key2] === "string"){
            jsonString += ",," + key2 + ',"' + obj["en"][key][key2]+'",,'+ lineEnd;
        }
        else if (typeof obj["en"][key][key2] === "object"){
            var fourthLevelKeys  = Object.keys(obj["en"][key][key2]);
                jsonString      += ',,' + key2 + ',,,' + lineEnd
            fourthLevelKeys.forEach(key3 => {
                if (typeof obj["en"][key][key2][key3] === "string") {
                    jsonString += ",,," + key3 + ',"' + obj["en"][key][key2][key3] + '",' + lineEnd;
                }
                else if (typeof obj["en"][key][key2][key3] === "object") {
                    var fifthLevelKeys  = Object.keys(obj["en"][key][key2][key3]);
                        jsonString     += ',,,' + key3 + ',,' + lineEnd
                    fifthLevelKeys.forEach(key4 => {
                        if (typeof obj["en"][key][key2][key3][key4] === "string") {
                            jsonString += ",,,," + key4 + ',"' + obj["en"][key][key2][key3][key4] + '"' + lineEnd;
                        }
                    })
                }
            })
        }
    });

});

fs.writeFileSync("generated.csv", jsonString, "utf8");