This is probably really simple, but I am new to working with JSON.
I am receiving this JSON string from an argument of an OSC message:
{"status":"ok","address":"\/workspaces","data":[{"version":"4.2.1","displayName":"Untitled Workspace","uniqueID":"82688E14-5E8F-428E-A781-8ABC920A5515","hasPasscode":false}]}
I am trying to convert it to a dictionary, so I can process the data. I have tried many answers on Stack Overflow, but this one seems the most relevant. However, it is throwing the error "The data couldn’t be read because it isn’t in the correct format."
Could someone advise why this string is the wrong format?
This is my code:
func didReceive(_ message: OSCMessage){
let jsonString = String(describing: message.arguments[0]!)
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
let dict = convertToDictionary(text: jsonString)
print(dict as Any)
}
Thanks so much!
Dan
EDIT: I have modified the code to remove the "\" which may have been contributing to the error. However it still throws the same error with the following code:
func didReceive(_ message: OSCMessage){
let jsonString = message.arguments[0] as! String
let jsonStringEdit = jsonString.replacingOccurrences(of: "\\", with: "")
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
let dict = convertToDictionary(text: jsonStringEdit)
print(dict as Any)
}
EDIT 2:
SOLVED!
It seems there was some kind of null/non-printable character at the end of the string. I have solved the issue for now by removing it before parsing it. I have used this code to remove it:
jsonString.remove(at: jsonString.index(before: jsonString.endIndex))
Thanks to everyone for your suggestions!