Search code examples
iosjsonswiftswift4jsonparser

How to parse a string data from array inside JSON another array in Swift 4


I have to show string data into a tableView.

{
"success": [
    [
        "An Ad with order id 2563 at location DLF, Delhi has been approved | 20 hours before|Shashank Tiwari"
    ],
    [
        "An Ad with order id 2539 at location V3S Mall has been approved | 1 week before|Shashank Tiwari"
    ],
    [
        "An Ad with order id 2515 at location Pacific Mall has been approved | 1 week before|Shashank Tiwari"
    ],
    [
        "An Ad with order id 2500 at location Ambience Mall has been rejected | 1 week before|Shashank Tiwari"
    ],
    [
        "An Ad with order id 2499 at location Vience Mall has been approved | 1 week before|Shashank Tiwari"
    ],
    [
        "An Ad with order id 2480 at location DLF, Delhi has been approved | 2 weeks before|Shashank Tiwari"
    ]
}

So I am parsing data as like below but not able to append data in to arrData Array.

           let json = try JSON(data:data
           let result = json["success"]                                           

                 print(result)


                    for arr in result.arrayValue {

                        self.arrData.compactMap{ $0 as? NSArray}
            }

Solution

  • If you want to flatten the array then compactMap is the wrong API.

    Use reduce

    let result = json["success"]
    let array = (result.arrayObject as! [[String]]).reduce([], +)
    self.arrData.append(contentsOf: array)
    
    • arrayObject returns [Any]?, you have to downcast it to the real type [[String]]
    • reduce transforms the two-dimensional array to an one-dimensional array.