46

Using SwiftyJSON how would I parse the following JSON array into a Swift [String]?

{ "array": ["one", "two", "three"] } 

I have tried this code, but it doesn't work for me:

for (index: String, obj: JSON) in json["array"] { println(obj.stringValue) } 

What would be the best way to handle this? Thank you.

4 Answers 4

97
{ "myArray": ["one", "two", "three"] } 

Using SwiftyJSON, you can get an array of JSON objects with:

var jsonArr:[JSON] = JSON["myArray"].arrayValue 

Functional programming then makes it easy for you to convert to a [String] using the 'map' function. SwiftyJson let's you cast string type with subscript '.string'

var stringArr:[String] = JSON["myArray"].arrayValue.map { $0.stringValue} 
Sign up to request clarification or add additional context in comments.

7 Comments

What is that s inside the map closure?
ah sorry, I edited now, it should be '$0' that's the shorthand argument for the map closure. .map() will iterate through every element of the json Array and assign the value to $0 each time.
Thanks. I'm facing kind of a similar issue with SwiftyJSON and arrays. I tried converting it like in your answer but it crashed with the error unexpectedly found nil while unwrapping an Optional value. I posted a separate question here. If you can, can you please have a look? Thanks.
This will fail in runtime when received json array that contains non-string values. I suggest changing to this: JSON["myArray"].arrayValue.map { "\($0)" }.
Just use .stringValue instead of .string and nil or wrong type just returns an empty string. JSON["myArray"].arrayValue.map { $0.stringValue }
|
9

SwiftyJSON lets you extract a String? using $0.string or a non optional String using stringValue with a default empty String value if the type doesn't match.

If you want to be sure to have an array of String with non false positives, use :

var stringArray = self.json["array"].array?.flatMap({ $0.string })

or in Swift 4.1

var stringArray = self.json["array"].array?.compactMap({ $0.string })

You can also replace self.json["array"].array by self.json["array"].arrayValue to have a [String] result instead of [String]?.

2 Comments

you can use flatMap to filter the strings that are equal to nil
Thanks @PabloMarrufo. Improved the reply with it and also compactMap introduced in Swift 4.1
5

You have a Dictionary which holds an Array which holds Strings. When you access a value in the Dictionary, it returns a simple Array of Strings. You iterate it like you would any array.

for obj in json["array"] { println(obj.stringValue) } 

Comments

4

Simply do this:

for stringInArray in json["array"]{ let value = stringInArray.1.stringValue } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.