You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何遍历含嵌套数组的对象,获取城市及对应所有社区列表

解决方案

首先注意:你提供的JSON存在格式问题,JSON的键名必须用双引号包裹,修正后的标准JSON如下:

{
  "cities": [
    {
      "City": "Islamabad",
      "Societies": [
        "Zaraj",
        "River Garden",
        "Soan Garden",
        "CBR Town",
        "PWD Society",
        "Pakistan Town"
      ]
    },
    {
      "City": "Lahore",
      "Societies": [
        "Lahore Smart City",
        "Bahria Town Lahore",
        "Gulberg Lahore",
        "Gulshan-e-Lahore"
      ]
    }
  ]
}

以下用Python实现你需要的遍历与格式输出:

import json

# 假设JSON数据已读取到变量data中(如果是从文件读取,可使用open()函数)
data = {
  "cities": [
    {
      "City": "Islamabad",
      "Societies": [
        "Zaraj",
        "River Garden",
        "Soan Garden",
        "CBR Town",
        "PWD Society",
        "Pakistan Town"
      ]
    },
    {
      "City": "Lahore",
      "Societies": [
        "Lahore Smart City",
        "Bahria Town Lahore",
        "Gulberg Lahore",
        "Gulshan-e-Lahore"
      ]
    }
  ]
}

# 遍历每个城市对象
for city_obj in data["cities"]:
    print(f"City: {city_obj['City']}")
    print("Societies:")
    # 遍历当前城市的社区数组
    for society in city_obj["Societies"]:
        print(society)
    # 打印空行分隔不同城市
    print()

输出结果:

City: Islamabad
Societies:
Zaraj
River Garden
Soan Garden
CBR Town
PWD Society
Pakistan Town

City: Lahore
Societies:
Lahore Smart City
Bahria Town Lahore
Gulberg Lahore
Gulshan-e-Lahore

内容的提问来源于stack exchange,提问作者user3305642

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 02:09:56