gpt4 book ai didi

javascript - 将 Google Sheet 转换为多级 JSON 数组

转载 作者:行者123 更新时间:2023-11-27 22:38:21 25 4
gpt4 key购买 nike

我正在尝试使用 Apps Script 将工作表中的值转换为多级 JSON

将值转换为单级 JSON 非常容易,如下所示:

[{
"name": "Bob Jones",
"phone": "555-555-5555",
"street": "123 Somewhere St.",
"city": "Nowhere",
"state": "ID",
"postal": 45632,
"country": "USA"
}]

但是,我想要的是:

[{
"name": "Bob Jones",
"phone": "555-555-5555",
"address": {
"street": "123 Somewhere St.",
"city": "Nowhere",
"state": "ID",
"postal": 45632,
"country": "USA"
}
}]

以下是用于格式化 JSON 的代码:

function makeJSON_(object, options) {
if (options.format == FORMAT_PRETTY) {
var jsonString = JSON.stringify(object, null, 4);
} else if (options.format == FORMAT_MULTILINE) {
var jsonString = Utilities.jsonStringify(object);
jsonString = jsonString.replace(/},/gi, '},\n');
jsonString = prettyJSON.replace(/":\[{"/gi, '":\n[{"');
jsonString = prettyJSON.replace(/}\],/gi, '}],\n');
} else {
var jsonString = Utilities.jsonStringify(object);
}
return jsonString;
}

设置“预转换”表来创建 JSON 子字符串很容易,但这并不灵活,而且维护起来很麻烦。

如何JSON.stringify()工作表数据自动创建子字符串?

最佳答案

要从您必须的 json 版本转到您想要的版本,您可以执行以下操作 --

var json = [{
"name": "Bob Jones",
"phone": "555-555-5555",
"street": "123 Somewhere St.",
"city": "Nowhere",
"state": "ID",
"postal": 45632,
"country": "USA"
}]

for (var i=0; i < json.length; i++){
var currentObj = json[i];
// make a temporary address object
var address = {};
// copy all the attributes over to the temp object
address.street = currentObj.street;
address.city = currentObj.city;
address.state = currentObj.state;
address.postal = currentObj.postal;
address.country = currentObj.country;
// add address to the original object
currentObj.address = address;
// get rid of the following attributes from parent
delete currentObj.street;
delete currentObj.city;
delete currentObj.state;
delete currentObj.postal;
delete currentObj.country;
}


console.log(json);

比替换字符串中的内容要容易得多。

http://codepen.io/anon/pen/XKOrXa

关于javascript - 将 Google Sheet 转换为多级 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38933709/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com