Reputation: 3
I have a string which contains a json in the following format:
var myString: String = "{key1: val1, key2: val2}"
How can I convert this to:
var myJson: [String: String] = ["key1": "val1", "key2": "val2"]
Since my string is not in format "{"key1": "val1", "key2": "val2"}"
, I am facing difficulty in parsing it through the following code snippet:
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
}
This function always returns nil for myString
Upvotes: 0
Views: 850
Reputation: 1
You know you should quote keys and values. Here is a easy way.
let jsonString = myString.replacingOccurrences(of: "(\\w+)", with: "\"$1\"", options: .regularExpression)
let result = convertToDictionary(text: jsonString)
Upvotes: 0
Reputation: 36792
you may have to do it the hard way. Something like this:
import SwiftUI
@main
struct TestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
extension String {
func trim() -> String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
struct ContentView: View {
var body: some View {
Text("testing")
.onAppear {
let myString: String = "{key1: val1, key2: val2, key3: val3}"
let myJson = transform(myString)
print("----> myJson: \(myJson)")
}
}
func transform(_ myString: String) -> [String : String] {
var result = [String : String]()
if myString.count > 2 { // case of {}
let temp1 = myString.dropFirst().dropLast()
let temp2 = temp1.split(separator: ",").map{String($0)}
for str in temp2 {
let temp3 = str.split(separator: ":").map{String($0)}
let (k,v) = (temp3[0].trim(),temp3[1].trim())
result[k] = v
}
}
return result
}
}
Upvotes: 1