skip to Main Content

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


  1. I believe the value of the key tax_amount is a Number rather than a String. It should be:

    let mock: [String: Any] = ["client_secret": "pi_3Q5hYZHbqLi", "tax_amount": 192, "total": 2424]
    
    if let taxAmount = mock["tax_amount"] as? Int {
        print(taxAmount)
        //192
    }
    
    Login or Signup to reply.
  2. 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

    1. Cast the Tax_amount to NSnumber, int, or maybe double

    anyways the issue is the datatype and how you cast it.

    probably..

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search