-3
"{Sunday:0,Monday:1,Tuesday:1,Wednesday:1,Thursday:1,Friday:1,Saturday:0}"

I have been trying to convert a string to a dictionary but its giving an error of data is invalid.

vadian
  • 274,689
  • 30
  • 353
  • 361

1 Answers1

-1

your json should look like this:

"{\"Sunday\":0,\"Monday\":1,\"Tuesday\":1,\"Wednesday\":1,\"Thursday\":1,\"Friday\":1,\"Saturday\":0}"

and then you can use this func

            func convertToJsonReturnDict(string: String) -> [String:Any]? {
             guard let data = s.data(using: .utf8) else { return [:]
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
                return json

            } catch {
                print(error)
                return [:]
            }
        }
Erez Mizrahi
  • 197
  • 6
  • Did you run the code with the given string? It will `catch`. And never print `localizedDescription` in a JSON decoding context. Printing just the `error` shows you the real error. – vadian Dec 10 '19 at 09:56
  • ok thank you if adjusted the code and found the problem with the string :) – Erez Mizrahi Dec 10 '19 at 10:14
  • Yes, but it doesn't answer the question if the string is as-is. – vadian Dec 10 '19 at 10:17