How to parse any stringified array such as "[\"Bob\", \"Tim\", \"Tina\"]" in Swift? It should return a JSON array such as ["Bob", "Tim", "Tina"].
Sorry if this is a duplicate question, but I could not find any answer for a generic stringified array where the structure of the array elements are not known.
Try doing it like this, Works for me every time:
let jsonText = "[\"Bob\", \"Tim\", \"Tina\"]"
var array: [String]?
if let data = jsonText.data(using: String.Encoding.utf8) {
do {
array = try JSONSerialization.jsonObject(with: data, options: []) as? [String]
if let myArray = array {
print(myArray)
}
} catch let error as NSError {
print(error)
}
}
It prints : ["Bob", "Tim", "Tina"]
Hope it helps!!