如何在Deluge中遍历嵌套数组并提取多级嵌套的地址信息?
在Deluge中提取嵌套JSON的地址信息
需求说明
需要从给定的JSON数据里,提取CurrentTenants数组下每个租户Address对象中的AddressLine1、AddressLine2和AddressLine3字段。原代码仅能获取第一层级数据,无法正确遍历嵌套的层级结构。
原JSON数据
{"Id": 0,"PropertyId": 0,"UnitId": 0,"UnitNumber": "string","LeaseFromDate": "2019-08-24","LeaseToDate": "2019-08-24","LeaseType": "None","LeaseStatus": "Active","IsEvictionPending": true,"TermType": "MonthToMonth","RenewalOfferStatus": "NotSet","CurrentTenants": [{"Id": 0,"FirstName": "string","LastName": "string","Email": "string","AlternateEmail": "string","PhoneNumbers": [{"Number": "string","Type": "NotSet"}],"CreatedDateTime": "2019-08-24T14:15:22Z","EmergencyContact": {"Name": "string","RelationshipDescription": "string","Phone": "string","Email": "string"},"DateOfBirth": "2019-08-24","SMSOptInStatus": "NotSet","Address": {"AddressLine1": "string","AddressLine2": "string","AddressLine3": "string","City": "string","State": "string","PostalCode": "string","Country": "UnitedStates"}}]}
原代码问题
原代码遍历CurrentTenants时,循环变量命名和后续赋值冲突,且错误地直接操作列表而非循环中的单个租户对象,导致无法正确获取每个租户的地址信息。
修正后的代码
for each row in rows { info row; UnitNumber = row.getJSON("UnitNumber"); info "UnitNumber is: " + UnitNumber; LeaseStartDate = row.getJSON("LeaseFromDate"); info "Lease Start Date is: " + LeaseStartDate; UnitId = row.getJSON("UnitId"); info "UnitID is: " + UnitId; // 获取租户列表 CurrentTenants = row.getJSON("CurrentTenants").toJSONList(); // 遍历每个租户 for each tenant in CurrentTenants { // 从当前租户对象中获取地址 tenantAddress = tenant.getJSON("Address"); // 提取地址行信息 addressLine1 = tenantAddress.getJSON("AddressLine1"); addressLine2 = tenantAddress.getJSON("AddressLine2"); addressLine3 = tenantAddress.getJSON("AddressLine3"); // 输出地址信息 info "AddressLine1: " + addressLine1; info "AddressLine2: " + addressLine2; info "AddressLine3: " + addressLine3; } }
关键修正点
- 循环
CurrentTenants时,使用tenant作为循环变量,指代列表中的单个租户对象 - 通过
tenant.getJSON("Address")获取当前租户的地址对象,而非直接操作整个租户列表 - 从地址对象中逐个提取
AddressLine1、AddressLine2、AddressLine3字段并输出
内容的提问来源于stack exchange,提问作者Pee
相关产品推荐
相关产品推荐

