I’m trying to extract the value of tax_amount from JSON string but this line
let taxAmountS = json["tax_amount"] as? String
triggers an error. A print out of json (json string) looks like it should work, here it is
["client_secret": pi_3Q5hYZHbqLi, "tax_amount": 192, "total": 2424]
It contains "tax_amount": 192. Can anyone assist with how to extract the value of 192 from the json string?
let task = URLSession.shared.dataTask(with: request, completionHandler: { [weak self] (data, response, error) in
guard let data = data,
let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any],
//let taxAmountS = json["tax_amount"] as? String,
let self = self else {
print("Error")
return
}
print("json is ", json)
taxAmt = (taxAmountS as NSString).doubleValue
2
Answers
I believe the value of the key
tax_amount
is a Number rather than a String. It should be:please check your data types. The issue is because you are attempting to cast tax_amount as a String, but the value is actually a Number (specifically, an Int in your case).
You can maybe properly extract the value
anyways the issue is the datatype and how you cast it.
probably..