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

如何从二维JSON数组提取所有公司名称?附代码报错与疑问

问题解决与说明

报错原因

你写的if let name = json[0]["name"] as? String报错,是因为Swift解析JSON后得到的json默认是Any类型,编译器没法直接识别json[0]的具体类型,自然也不能接着用["name"]下标取值。得先把顶层的JSON转成数组+字典的明确类型才行。

JSON索引确认

没错,你提供的JSON是一个顶层数组,数组的元素就是每个公司的字典对象,数组的索引确实是[0], [1], [2]这种从0开始的顺序索引,对应三个公司的条目。

获取所有公司名称的代码示例

假设你已经完成了JSON数据的解析(比如从文件/网络拿到Data后转成了json变量),可以这样处理来得到所有name的数组:

// 先把顶层JSON转成[[String: Any]]类型(数组里装字典)
if let companiesArray = json as? [[String: Any]] {
    // 遍历数组,提取每个字典里的"name",compactMap会自动过滤掉解析失败的nil值
    let allCompanyNames = companiesArray.compactMap { companyDict in
        companyDict["name"] as? String
    }
    // 现在allCompanyNames就是你要的数组:["Marta Inc", "Laud", "Lynx"]
    print(allCompanyNames)
}

如果是直接从本地JSON文件读取的场景,完整的示例代码可以是这样:

// 读取本地JSON文件
guard let url = Bundle.main.url(forResource: "companies", withExtension: "json"),
      let data = try? Data(contentsOf: url),
      let json = try? JSONSerialization.jsonObject(with: data, options: []) else {
    print("JSON解析失败")
    return
}

// 提取所有name
if let companiesArray = json as? [[String: Any]] {
    let allCompanyNames = companiesArray.compactMap { $0["name"] as? String }
    print(allCompanyNames)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 10:47:05