I have a json that I could parse with SwiftyJSON :

if let title = json["items"][2]["title"].string {
     println("title : \(title)")
}

Works perfectly.

But I couldn't loop through it. I tried two methods, the first one is

// TUTO :
//If json is .Dictionary
for (key: String, subJson: JSON) in json {
    ...
}
// WHAT I DID :
for (key: "title", subJson: json["items"]) in json {
    ...
}

XCode不接受for循环声明.

第二种方法:

// TUTO :
if let appArray = json["feed"]["entry"].arrayValue {
     ...
}
// WHAT I DID :
if let tab = json["items"].arrayValue {
     ...
}

XCode不接受if语句.

我做错了什么?

推荐答案

如果您希望遍历json["items"]个数组,请try :

for (key, subJson) in json["items"] {
    if let title = subJson["title"].string {
        println(title)
    }
}

对于第二种方法,.arrayValue返回non Optional数组,您应该改用.array:

if let items = json["items"].array {
    for item in items {
        if let title = item["title"].string {
            println(title)
        }
    }
}

Json相关问答推荐

替换字符串中特殊字符的Jolt变换

Moshi:序列化 List 时出现问题

如何将具有相同 struct 的多个JSON文件中的对象数组合并成一个数组?

如何使NiFi将数据库单列中的多个值转化为Solr索引中的数组?

ORA-01422: 精确提取返回的行数超过了与 json 对象组合的请求数

使用 Jolt 变换将平面 json 转换为具有多个数组的嵌套 Json

提交后使用 Rails 7 结合 JSON 标签进行标记

我无法在 Go - Gin 中解析日期/时间

使用 Ansible 解析来自 Juniper 交换机的 JSON 输出

自定义将 struct 解组为切片映射

杰克逊 2.0 和 Spring 3.1

使用 boost 属性树读取 int 数组

Jackson 的@JsonView、@JsonFilter 和 Spring

从 HttpResponse 获取 json

将json字符反序列化为枚举

以 unicode 将 pandas DataFrame 写入 JSON

消息通知产生此内容无法显示

有没有办法折叠 Postman 中的所有 json 字段

为什么 JavaScript 的 eval 需要括号来判断 JSON 数据?

YAML 将 5e-6 加载为字符串而不是数字