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

  • 3
    [Simple and clean way to convert JSON string to Object in Swift](https://stackoverflow.com/questions/25621120/simple-and-clean-way-to-convert-json-string-to-object-in-swift) – Nirav D Sep 23 '22 at 03:56
  • @NiravD I'm try but results alway return nil – a programer Sep 23 '22 at 04:07
  • 1
    What you tried update your question with what your tried – Nirav D Sep 23 '22 at 04: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 – Nirav D Sep 23 '22 at 04:14
  • I'm trying ***as? [[String : Any?]]*** the result is still nil – a programer Sep 23 '22 at 04:17
  • 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]]` – Nirav D Sep 23 '22 at 04:19
  • I'm sorry but results is still nill – a programer Sep 23 '22 at 04:23
  • It work when wrapped in a double quote of key. But is there any way to make it work even without wrapping quotes in key. I also removed ? after Any – a programer Sep 23 '22 at 04:25
  • @khjfquantumjj Hi, I think issue of me is Array of Dictionary not JSON object – a programer Sep 23 '22 at 04:28
  • 1
    No, you need to add a double quote around the key, valid JSON always have double quote around key – Nirav D Sep 23 '22 at 04:31
  • 1
    You need to learn the terminology right: your desired result is not array, it's dictionary; your original is not a string, it's an array of JSON objcts (with quotes escaped, but unclear if this escaping is artifact of showin the value or it's actually escaped... – timbre timbre Sep 23 '22 at 04:31
  • 1
    And there's a gazillion of answers on how to convert an array of json objects to dictionary for swift. – timbre timbre Sep 23 '22 at 04:32
  • maybe my problem is solved – a programer Sep 23 '22 at 04:36

0 Answers0