How to parse a JSON array for an array in Swift

I am trying to parse JSON which is below

[ { "People": [ "Jack", "Jones", "Rock", "Taylor", "Rob" ] }, { "People": [ "Rose", "John" ] }, { "People": [ "Ted" ] } ] 

into the array, which result in [[“Jack”, “Jones”, “Rock”, “Taylor”, “Rob”], [“Rose”, “John”], [“Ted”]]

which is an array of arrays.

I tried with the code below

 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? [AnyObject] for people in peoplesArray! { print(people) } } 

when I type "people" I get o / p like

 { People = ( Jack, "Jones", "Rock", "Taylor", "Rob" ); } { People = ( "Rose", "John" ); } ..... 

I am confused how to make out when it "People" is repeated 3 times

Trying to display content in a UITableView, where my 1st cell has a "Jack" .. "Rob", and the second cell has a "Rose", "John" and a third cell as "Ted"

PLease will help me understand how to achieve this.

+5
source share
5 answers
  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) } 
+4
source

You can do it in an elegant and safe way using Swift 4 Decodable

First determine the type of the people array.

 struct People { let names: [String] } 

Then make it Decodable so that it can be initialized using 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. Eg: print(error) // Insert error handling here } 

Finally, to get your linear array of names, you can do

 let names = people.flatMap { $0.names } // => ["Jack", "Jones", "Rock", "Taylor", "Rob", "Rose", "John", "Ted"] 
+2
source

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 try to do jsonserialization, you have to drop it until the expected result. So, first you have an array of objects, then you have a dictionary with String: Any, then you get 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)") } 
0
source

I couldn’t insert it in the comment, is it too long or something

 static func photosFromJSONObject(data: Data) -> photosResult { do { let jsonObject : Any = try JSONSerialization.jsonObject(with: data, options: []) print(jsonObject) guard let jsonDictionary = jsonObject as? [NSObject : Any] as NSDictionary?, let trackObject = jsonDictionary["track"] as? [String : Any], let album = trackObject["album"] as? [String : Any], let photosArray = album["image"] as? [[String : Any]] else { return .failure(lastFMError.invalidJSONData) } } 

And json was something like:

 { artist: { name: Cher, track: { title: WhateverTitle, album: { title: AlbumWhatever, image: { small: "image.px", medium: "image.2px", large: "image.3px"} .... 
0
source

let's say json is 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!) } }) 

Now you can use arrayOfData .: D

0
source

Source: https://habr.com/ru/post/1263901/


All Articles