如何搜索非常大的json文件?

时间:2016-05-21 23:15:18

标签: ios swift swifty-json

我有一个巨大的json文件,我正在尝试从文件中提取信息,但是要追踪路径是很大的方法。我可以使用ID过滤它吗? JSON code 我需要选择课程名称,例如enter image description here

  let urlString = "Can't provide the url"
    if let url = NSURL(string: urlString){
        if let data = try? NSData(contentsOfURL: url, options: []){
            let json = JSON(data: data)
            parseJSON(json)
        }
    }
}

func parseJSON(json: JSON){
    for (index: String, subJson: JSON) in json {

    }
}

1 个答案:

答案 0 :(得分:2)

我想出了一种基于深度优先的方法,可以根据谓词找到给定的JSON对象。

我把它变成了一个扩展名:

extension JSON {

    func find(@noescape predicate: JSON -> Bool) -> JSON? {

        if predicate(self) {
            return self
        }
        else {
            if let subJSON = (dictionary?.map { $0.1 } ?? array) {
                for json in subJSON {
                    if let foundJSON = json.find(predicate) {
                        return foundJSON
                    }
                }
            }
        }

        return nil
    }
}

例如,要搜索具有给定JSON字段的id对象(例如问题中),您可以使用此方法:

let json = JSON(data: data)
let predicate = {
    (json: JSON) -> Bool in
    if let jsonID = json["id"].string where jsonID == "plnMain_ddlClasses" {
        return true
    }
    return false
}
let foundJSON = json.find(predicate)

在这种情况下,如果您需要继续并找到您要查找的类,您可能需要:

let classes = foundJSON?["children"].arrayValue.map {
    $0["html"].stringValue
}

更新 - 查找全部

func findAll(@noescape predicate predicate: JSON -> Bool) -> [JSON] {
    var json: [JSON] = []
    if predicate(self) {
        json.append(self)
    }
    if let subJSON = (dictionary?.map{ $0.1 } ?? array) {
        // Not using `flatMap` to keep the @noescape attribute
        for object in subJSON {
            json += object.findAll(predicate: predicate)
        }
    }
    return json
}
相关问题