0

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.

1
  • you cant, ["Bob", "Tim", "Tina"] is not an JSON array, it is still an array of String Commented Mar 1, 2018 at 7:52

2 Answers 2

2

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!!

Sign up to request clarification or add additional context in comments.

1 Comment

@conundrum Sure I'll add the support for all kind of JSON serialization
0
extension String
{      
    func decodeUrl() -> String
    {
        return self.removingPercentEncoding!
    }
}

extension Data
{
    func dataToJSON() -> Any? {
        do {
            return try JSONSerialization.jsonObject(with: self, options: [])
        } catch let myJSONError {
            print(myJSONError)
        }
        return nil
    }
}

Usage :

if let data = your_stringified_array.decodeUrl().data(using: String.Encoding.utf8) {
            if let jsonc = data.dataToJSON() {
                print(jsonc)
            }
        }

Result is in AnyObject.

1 Comment

I marked the other one as correct as it came earlier. I could not mark both as correct. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.