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

How do I search a very very large json file?

我有一个巨大的 json 文件,我正试图从该文件中提取信息,但要找到路径实在是太大了。我可以使用 id 过滤它吗? JSON code I need to pick up course names i.e.

  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 {

    }
}

我想出了一种基于谓词查找给定 JSON 对象的深度优先方法。

我把它做成了扩展:

extension JSON {

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

        if predicate(self) {
            return self
        }
        else {
            if let subJSON = (dictionary?.map { [=10=].1 } ?? array) {
                for json in subJSON {
                    if let foundJSON = json.find(predicate) {
                        return foundJSON
                    }
                }
            }
        }

        return nil
    }
}

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

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 {
    [=12=]["html"].stringValue
}

更新 — 查找全部

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