Swift

Swift4でJSONをパースする

文字列を、JSONオブジェクト(配列とディクショナリの組み合わせ)に変換します。

import Foundation

let str = """
    [{"name":"John","age":37},{"name":"Tim"}]
    """

struct ParseError: Error {}
func parse(json: String) throws {
    guard let data = json.data(using: .utf8) else {
         throw ParseError()
     }
    let json = try JSONSerialization.jsonObject(with: data)
    guard let rows = json as? [[String:Any]] else {
        throw ParseError()
    }
    for row in rows {
        let name = row["name"] ?? ""
        let age = row["age"] ?? 0
        print("\(name) is \(age)")
    }
}

do {
    try parse(json: str)
} catch {
    print("error")
}

参考: https://developer.apple.com/swift/blog/?id=37