Search code examples
jsonswiftaws-api-gatewayaws-amplifyswifty-json

Parse JSON response with SwiftyJSON


I have the following code and I am trying to get values using SwiftyJSON:

let string =
    """
        {"ResponseMetadata": {"RequestId": "b5d6ecad-e050-4d1f-8429-74a2775a6fe9", "HTTPStatusCode": 200, "HTTPHeaders": {"x-amzn-requestid": "b5d6ecad-e050-4d1f-8429-74a2775a6fe9", "content-type": "application/json", "content-length": "271", "date": "Tue, 22 Dec 2020 22:45:17 GMT"}, "RetryAttempts": 0}, "numberOfRecordsUpdated": 0, "records": [[{"stringValue": "6998DFFE-A9CF-4BEA-86AD-C356BB865E27"}, {"stringValue": "[email protected]"}, {"stringValue": "David"}, {"stringValue": "Craine"}, {"stringValue": "dcraine"}, {"stringValue": "vendor1"}, {"stringValue": "vendor1_werw8"}]]}
    """
    
let body = JSON(string)
print(">>>>>>>>> \(body["records"])")

This returns null for body["records"].

I validated this response using https://jsonformatter.curiousconcept.com/#, so I am assuming it is in the correct format. Can anyone help please?


Solution

  • Try changing this line:

    let body = JSON(string)
    

    and call the init(parseJSON:) initializer of JSON that takes a String as parameter, like this:

    let body = JSON(parseJSON: string)