johnson johnson - 6 months ago 72
Swift Question

How do I search a very very large json file?

I have a enormous json file and I am trying to extract information form the file, but it is way to big to track down the path. Could I filter it using the id? JSON code I need to pick up course names i.e.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 {

}
}

Answer

I came up with a depth-first way of finding a given JSON object based on a predicate.

I made it into an extension:

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
    }
}

For instance, to search for the JSON object with a given id field, such as in the question, you can use the method as such:

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)

In this case, if you need to continue and find the classes you were looking for, you would want:

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