![](/img/trans.png)
[英]How to parse a JSON object with nested arrays in google apps script
[英]How to parse nested JSON object arrays?
我们正在为 WeClapp ( https://www.weclapp.com/api2/ ) 编写扩展。 WeClapp 中的自定义属性几乎可以添加到所有数据类型中。 这些属性可通过嵌套的 JSON 对象数组访问。
接口示例:
export interface ICustomAttribute {
attributeDefinitionId: string;
booleanValue?: boolean;
dateValue?: number;
entityId?: string;
numberValue?: number;
selectedValueId?: string;
stringValue?: string;
}
export interface IContact {
id: string;
...
customAttributes: ICustomAttribute[];
email: string;
...
}
响应示例:
{
"id": "4317",
...
"customAttributes": [
{
"attributeDefinitionId": "4576",
"booleanValue": null,
"dateValue": null,
"entityId": null,
"numberValue": null,
"selectedValueId": null,
"selectedValues": null,
"stringValue": "Test"
},
{
"attributeDefinitionId": "69324",
"booleanValue": true,
"dateValue": null,
"entityId": null,
"numberValue": null,
"selectedValueId": null,
"selectedValues": null,
"stringValue": null
}
],
...
"email": "name@domain.com",
...
}
除了[customAttributes]
属性之外,访问 IContact(以下示例中的联系人)属性没有问题。 如何访问和操作数据?
在以下示例中contact = IContact
:
console.log(contact);
输出:
[
{
id: '102570',
...
customAttributes: [ [Object], [Object], [Object], [Object] ],
...
}
]
console.log(contact.id); //Outputs: 102570
console.log(contact.customAttributes); //Outputs: undefined
JavaScript 数组扩展( length
、 ForEach
、 ...)在[contact.customAttributes]
上不可用,因为它是undefined
:
let attributes = new Array(0);
attributes = attributes.concat(record.customAttributes);
console.log(attributes); // Outputs: [undefined]
我也尝试更改接口并尝试重新解析:
export interface IContact {
id: string;
...
customAttributes: string;
email: string;
...
}
...
let attributes Array<ICustomAttribute> = JSON.Parse(record.customAttributes);
我不知道为什么我不能访问数组。 最奇怪的是设置属性不会抛出任何错误:
let attribute: ICustomAttribute = { attributeDefinitionId: "4576", stringValue: "Test" };
let contact = { customAttributes: [attribute] };
这个新条目可以发布和返回,如上所示。
JSON.stringify(contact)
输出:
[{"id":"102871",...,"customAttributes":[{"attributeDefinitionId":"4229"},{"attributeDefinitionId":"46381"},{"attributeDefinitionId":"69316"},{"attributeDefinitionId":"98781","stringValue":"77b5d0f1-b1a4-4957-8ea2-ea95969e3c03"}],...,"email":"name@domain.com"}]
console.log(contact["customAttributes"])
是undefined
。
试试console.log(contact['customAttributes']);
如果您的console.log(contact)
产生:
[
{
id: '102570',
...
customAttributes: [ [Object], [Object], [Object], [Object] ],
...
}
]
那么这表明contact.customAttributes
不存在。 contact
是一个对象数组,要到达第一个对象,您需要contact[0].customAttributes
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.