3

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.

1
  • I am using xcode 7.3 so it is swift 2.2 right? Commented Oct 21, 2016 at 4:07

2 Answers 2

7

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)
   }
 }
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you sir @vadian I cant still parsed it to string array but with your help I've already got the jsonarray dictionary. here is the snippet code image.prntscr.com/image/91e86ca71c474c28ae7b9199ecca65b0.png
and here is the result image.prntscr.com/image/cbed3c440f2e4d21871b4539dd137ab0.png i've printed the weights and it got the jsonarray. But the following lines didn't parse it. Thank you so much!
0

This may be a bit more of a swifty answer. What we're doing here is iterating over the json array using map and returning a dictionary object for each item in the array. The map function will of course create its own array and append each dictionary object to it, before returning the entire array stored in the weights variable. May brain is nearly fried so if I didn't get that quite right let me know.

let swiftyJSON = JSON(data: data!)
let weights = swiftyJSON["weights"].arrayValue.map {["date": $0["date"].stringValue, "weights": $0["weights"].stringValue]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.