1

I have string:

content (String) : "[{id: \"10884\", name: \"Henry\"}, {id: \"85474\", name: \"Jack\"}]"

How can I convert this string to array

Desired results:

[{id: "10884", name: "Henry"}, {id: "85474", name: "Jack"}]

I'm trying:

let data = content.data(using: .utf8, allowLossyConversion: false)

let stringsArray = try? JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String: AnyObject]

print(stringsArray)

But stringsArray print is nil

I'm using swift version 5

I'm newbie IOS. Many thanks

13
  • 3
    Simple and clean way to convert JSON string to Object in Swift Commented Sep 23, 2022 at 3:56
  • 1
    What you tried update your question with what your tried Commented Sep 23, 2022 at 4:08
  • 1
    You are casting result into the dictionary it is an array of dictionary also don't force wrap your data, this will crash your app if the data is nil, instead of that use if let or guard let to optionally wrapped data Commented Sep 23, 2022 at 4:14
  • 1
    Its because your key id and name also need to be wrapped in a double quote in JSON string also you don't need to add ? after Any it is simply [[String : Any]] Commented Sep 23, 2022 at 4:19
  • 1
    No, you need to add a double quote around the key, valid JSON always have double quote around key Commented Sep 23, 2022 at 4:31

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.