MNM MNM - 4 months ago 10
JSON Question

Parse out a value from json in swift

I am trying to parse out a int value in the variable but its returning nil or 0 The value I want is from the customer_group_id. I am using swift. I have parsed out other information from the json file, but it keeps messing up at this stage.

print("My Loyalty rank: " , newJson["loyalty_rank"][0]["customer_group_id"].string)
myRank = newJson["loyalty_rank"][0]["customer_group_id"].intValue


Here is the json file

{ "id":298,
"name":"桃子 桜",
"total_points_earned":164,
"points_available_to_spend":164,
"loyalty_rank":{
"customer_group_id":9,
"name":"Baby Bee",
"ratio":1
},
"order_history":[
{ }
],
"barcode_id":"C-00000298"
}

Answer

loyalty_rank is [String:AnyObject] means its Dictionary not an array ...

try to print it like

     // if its string
     print("My Loyalty rank: " , newJson["loyalty_rank"]["customer_group_id"].string)

     // if its Int
     print("My Loyalty rank: " , newJson["loyalty_rank"]["customer_group_id"].intValue)

Better to use if let or guard like

    if let customerId = newJson["loyalty_rank"]["customer_group_id"].intValue{
        // customerId is int value
   }
   else{
       // not an int
   }