Search code examples
jsonswift3

Get a value based on key in swift 3


I'm using following code to serialise json response from web server and I try to get all the key value pairs.

do {
    let resultJson = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]

    if let dictionary = resultJson as? [String: Any] {
        if let nestedDictionary = dictionary["Part"] as? [String: Any] {
            // access nested dictionary values by key
            for (key, value) in dictionary {
                // access all key / value pairs in dictionary
                print(key)
                print(value)
            }
        }
    }
} catch {
      print("Error -> \(error)")
}

My response from server is

["ProductInfo": {

}, "PartTax": <__NSCFArray 0x166cff60>(
{

},
{

},
{

}
)
, "PartLog": <__NSCFArray 0x166d0a70>(
{

},
{

},
{

},
{

}
)
, "ReceivedItem": {

}, "PartPriceLevel": <__NSCFArray 0x166cfd50>(
{

},
{

},
{

},
{

},
{

},

{

},
{

},
{

}
)
, "Part": {
    "auxiliary_desc" = "Connie's keyman";
    barcode = 0123456789012;
    "category_id" = 57022;
    "primary_desc" = "MK25T/S600T Regulator combo ";
    stock = 0;
    "store_id" = 49537;
}]

My response has lot of nested arrays in that "Part" is one of the nested array and I want to print all of its key value pair. Here when I print resultJson I can see my whole response .I followed https://developer.apple.com/swift/blog/?id=37. Can some one help me to fix this code. Thanks in advance.


Solution

  • do {
        let resultJson = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]
    
        if let dictionary = resultJson as? [String: Any] {
            if let nestedDictionary = dictionary["Part"] as? [String: Any] {
                // access nested dictionary values by key
                for (key, value) in nestedDictionary {
                    // access all key / value pairs in dictionary
                    print(key)
                    print(value)
                }
            }
        }
    } catch {
        print("Error -> \(error)")
    }