Search code examples
jsonswiftamazon-web-servicesaws-lambdaswifty-json

Parsing JSON answer from an AWS Lambda function


I just got an AWS Lambda function working as I expect, but I am having trouble parsing its JSON answer. I am using SwiftyJSON for that.

Here is my test code:

let json = JSON(task.result!)
print("SWyJSON: \(json)")

if let jsonDic = json.dictionary {
    print("SWyJSON2a: \(jsonDic)")
    print("SWyJSON2b: \(String(describing: jsonDic["body"]!))")
    if let x = json.dictionary?["body"]?.dictionary {
        print("SWyJSON2c: \(String(describing: x["Users"]))")
    }
}

SWyJSON: {
  "inBound" : "9bf69.....14d5ac4",
  "body" : "{\"Users\":[{\"Username\":\"test1\",\"Attributes\":[{\"Name\":\"email\",    \"Value\":\"[email protected]\"}],\"UserCreateDate\":\"2019-06-03T02:53:03.300Z\",  \"UserLastModifiedDate\":\"2019-06-03T02:53:56.580Z\",\"Enabled\":true,\"UserStatus\":\"CONFIRMED\"}]}",
  "statusCode" : 200
}

SWyJSON2a: ["inBound": 9bf69.....14d5ac4, "body": {"Users":[{"Username":"test1","Attributes":[  {"Name":"email","Value":"[email protected]"}],"UserCreateDate":"2019-06-03T02:53:03.300Z",    "UserLastModifiedDate":"2019-06-03T02:53:56.580Z","Enabled":true,"UserStatus":"CONFIRMED"}]}, "statusCode":     200]

SWyJSON2b: {"Users":[{"Username":"test1","Attributes":[{"Name":"email","Value":"[email protected]"}],   "UserCreateDate":"2019-06-03T02:53:03.300Z","UserLastModifiedDate":"2019-06-03T02:53:56.580Z", "Enabled":true,"UserStatus":"CONFIRMED"}]}

My question is: what is wrong in the code so that the last print is not giving any result?

SWyJSON, SWyJSON2a and SWyJSON2b are showing some result in the Xcode debugging console as I expect, but not SWyJSON2c. Where I would expect something like:

"Users":[{"Username":"test1","Attributes":[{"Name":"email","Value":"[email protected]"}],   "UserCreateDate":"2019-06-03T02:53:03.300Z","UserLastModifiedDate":"2019-06-03T02:53:56.580Z", "Enabled":true,"UserStatus":"CONFIRMED"}]

or:

[{"Username":"test1","Attributes":[{"Name":"email","Value":"[email protected]"}],   "UserCreateDate":"2019-06-03T02:53:03.300Z","UserLastModifiedDate":"2019-06-03T02:53:56.580Z", "Enabled":true,"UserStatus":"CONFIRMED"}]

Solution

  • body value is a string not a dictionary so change

    if let x = json.dictionary?["body"]?.dictionary {
    

    to

    if let x = json.dictionary?["body"]?.string {
    
        let data = Data(x.utf8)
    
        let content = try? JSONSerialization.jsonObject(with:data, options: [])
    
        if let _  =  content as? [[String:Any]] { // array 
    
           let res = try?  JSONDecoder().decode([Root].self,from:data)
    
           print(res)
    
        }
        else if let dic  =  content as? [String:Any] {  {
    
           guard let users = dic["Users"] else { return } // dictionay
    
           guard let jsonData = try? JSONSerialization.data(withJSONObject: users, options:[]) else { return }
    
           let res = try?  JSONDecoder().decode([Root].self,from:jsonData)
    
           print(res)
    
        }
    }
    
    
      // MARK: - Element
    struct Root: Codable {
        let username: String
        let attributes: [Attribute]
        let userCreateDate, userLastModifiedDate: String
        let enabled: Bool
        let userStatus: String
    
        enum CodingKeys: String, CodingKey {
            case username = "Username"
            case attributes = "Attributes"
            case userCreateDate = "UserCreateDate"
            case userLastModifiedDate = "UserLastModifiedDate"
            case enabled = "Enabled"
            case userStatus = "UserStatus"
        }
    }
    
    // MARK: - Attribute
    struct Attribute: Codable {
        let name, value: String
    
        enum CodingKeys: String, CodingKey {
            case name = "Name"
            case value = "Value"
        }
    }