Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSONArray to string array using SwiftyJSON

Well I am really new Swift and I've used swiftyJSON to have an ease in parsing JSON data coming from the API.

I have a data response which looks like this:

[
   {
     "fname": < String value>
     "mname": < String value>
     "lname": < String value>
     "weights": [
          {
            "date": <String value>, 
            "weight": <String value> 
          },
          {
            "date": <String value>,
            "weight": <String value>
          }
]

For my swiftyJSON parsing way, here is my code

let swiftyJSON = JSON(data: data!)
for item in swiftyJSON.arrayValue{
    self.firstName = item["fname"].stringValue
    self.middleName = item["mname"].stringValue
    self.lastName = item["lname"].stringValue
    //JSON Array "weights" code snippet below
}

For the names I've parsed it to string but with the "weights". I have no idea how to do that. I've tried it using this:

for key in item["weights"]["weight"].arrayValue{
   self.allWeights.append(key.stringValue)
}

And it is not working. Can someone help me with this? thanks a lot.

like image 608
Reginald Avatar asked Jul 28 '26 22:07

Reginald


1 Answers

weights contains an array of dictionaries

...   
if let weights = item["weights"].array {
   for weightItem in weights {
     let date = weightItem["date"].stringValue
     let weight = weightItem["weight"].stringValue
     print(date, weight)
   }
 }
like image 78
vadian Avatar answered Jul 31 '26 14:07

vadian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!