How to parse Array of JSON to array in Swift
You can do this in an elegant and type safe way leveraging Swift 4 Decodable
First define a type for your people array.
struct People {
let names: [String]
}
Then make it Decodable
, so that it can be initialised with a JSON.
extension People: Decodable {
private enum Key: String, CodingKey {
case names = "People"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Key.self)
self.names = try container.decode([String].self, forKey: .names)
}
}
Now you can easily decode your JSON input
guard
let url = Bundle.main.url(forResource: "People", withExtension: "json"),
let data = try? Data(contentsOf: url)
else { /* Insert error handling here */ }
do {
let people = try JSONDecoder().decode([People].self, from: data)
} catch {
// I find it handy to keep track of why the decoding has failed. E.g.:
print(error)
// Insert error handling here
}
Finally to get get your linear array of names you can do
let names = people.flatMap { $0.names }
// => ["Jack", "Jones", "Rock", "Taylor", "Rob", "Rose", "John", "Ted"]
what you have here is first an array of 3 objects. each object is a dictionary where the key is people and the value is an array of strings. when you're trying to do jsonserialization, you have to cast it down to the expected result. So you have first an array of objects, then you have a dictionary with String: Any, then you obtain an array of String
let peoplesArray = try! JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: path)), options: []) as? [AnyObject]
guard let peoplesObject = peoplesArray["people"] as? [[String:Any]] else { return }
for people in peoplesObject {
print("\(people)")
}
let assume that the json is the encoded data
var arrayOfData : [String] = []
dispatch_async(dispatch_get_main_queue(),{
for data in json as! [Dictionary<String,AnyObject>]
{
let data1 = data["People"]
arrayOfData.append(data1!)
}
})
You can now use the arrayOfData. :D
var peoplesArray:[Any] = [
[
"People": [
"Jack",
"Jones",
"Rock",
"Taylor",
"Rob"
]
],
[
"People": [
"Rose",
"John"
]
],
[
"People": [
"Ted"
]
]
]
var finalArray:[Any] = []
for peopleDict in peoplesArray {
if let dict = peopleDict as? [String: Any], let peopleArray = dict["People"] as? [String] {
finalArray.append(peopleArray)
}
}
print(finalArray)
output:
[["Jack", "Jones", "Rock", "Taylor", "Rob"], ["Rose", "John"], ["Ted"]]
In your case, it will be:
if let path = Bundle.main.path(forResource: "People", ofType: "json") {
let peoplesArray = try! JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: path)), options: JSONSerialization.ReadingOptions()) as? [Any]
var finalArray:[Any] = []
for peopleDict in peoplesArray {
if let dict = peopleDict as? [String: Any], let peopleArray = dict["People"] as? [String] {
finalArray.append(peopleArray)
}
}
print(finalArray)
}