Learn how to extract strings using SwiftyJSON.

Asked 2 years ago, Updated 2 years ago, 54 views

Using Xcode 7.0
We are developing under Swift 2.0 environment.

Example JSON data:

[
    {"Name": "Yoshiro", "sex": "Man", 
    {"Name": "Fune", "sex": "Woman", 
    {"Name": "Kojiro", "sex": "Man"}
]

From this JSON data

 ["Yoshiro", "Fune", "Kojiro"]

I would like to create an array of .

My code (partial omitted)....

var delaylineArray: String!=[]

-------------------------------------

let json = JSON (data:data!)

while0<1{
    iflet line=json[0]["Name"].string{
        self.delaylineArray.append(line)
    } else{
        break
    }
}

-------------------------------

I thought about taking it out like this, but
If you print delayLineArray,

["Yoshiro", "Yoshiro", "Yoshiro", "Yoshiro", "Yoshiro", "Yoshiro", "Yoshiro", "Yoshiro", "Yoshiro", "Yoshiro", "Yoshiro", "Yoshiro", "Yoshiro", "Yoshiro", "Yoshiro

The array will look like this.

I don't know how to access objects that contain funes and complications, so
I would appreciate it if you could let me know.

swift json

2022-09-30 11:12

1 Answers

Only the first elements will be arranged.

while0<1{
    iflet line=json[0]["Name"].string{

This is because you always get the first element as json[0].

Loop JSON one at a time, or

 for (index, subJson): (String, JSON) in json {
    iflet line=json["Name"].string{
        self.delaylineArray.append(line)
    }
}

If you know that the outermost element is an array, you can simply write using map.

let delaylineArray=json.arrayValue.map {$0["Name".stringValue}


2022-09-30 11:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.