0
votes

I am having issue to grab value from JSON in swift 4.

{
    "meta": {"expiration": 0,"flags": 33456},
    "json": "{\"key\":\"string\",\"value\":{\"failed_attempts\":\"1\"}}",
    "xattrs": {}
}

The code I have tried

if let resultData = responseBody["json"] as? [String: AnyObject]{

   if let val = resultData["value"] as? [String: AnyObject]{

      if let attempt = val["failed_attempt"] as? String {
         print(attempt)

         }
    }
}

I have tried to print below line, it correctly prints all object inside json array but when ever i tried to add a return type as [String: AnyObject] it returns nil value. Could someone please give me some advise.

response["json"]

2
what's resultData ?Ali Abbas
You should use Codable for Swift 4Scriptable
@AliAbbas I have edited the code to reflect resultData.sjgmamer
the [] brackets suggest that your JSON at the top level is an arrayScriptable
Just ran query again from postman, and its a curly bracket actually.sjgmamer

2 Answers

1
votes

Replace AnyObject with Any. Dictionaries are structs, not objects, so that cast will fail.

I would also suggest learning about Codable to handle JSON in the future.

Edit:

You'll need to serialize your data into a JSON object first. The Data class is not automatically converted to JSON.

do {
    let jsonRoot = try JSONSerialization.jsonObject(with: responseBody, options: []) as! [String: Any]
    if let json = jsonRoot["json"] as? [String: Any],
        let val = json["value"] as? [String: Any],
        let attempt = val["failed_attempt"] as? String {
        print(attempt)
    }
} catch {
    print("Invalid data", error)
}
0
votes

The best way is to use Codable, that's why, according to your JSON string I create Codable structures.

The JSONString should be:

let jsonString = """
{ "meta": { "expiration":0, "flags":33456 },
  "json": { "key":"String",
           "value":{ "failed_attempt":"3" },
         },
 "xattrs":{ "someAttribute":"someValue"}
}
"""

And the structures:

struct Response: Codable {
    var meta: MetaData
    var json: JSONResponse
    var xattrs: Xattrs?
}

struct MetaData: Codable {
    var expiration: Int
    var flags: Int
}

struct JSONResponse: Codable {
    var key: String
    var value: JSONValue
}

struct JSONValue: Codable {
    var failed_attempt: String
}

struct Xattrs: Codable {
    var someAttribute: String
}

if let jsonData = jsonString.data(using: .utf8)
{
    let myStruct = try? JSONDecoder().decode(Response.self, from: jsonData)
    print(myStruct?.json.value.failed_attempt)
}