MNM MNM - 1 year ago 47
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":"桃子 桜",
"name":"Baby Bee",
{ }

Answer Source

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
       // not an int