Если фигурные кавычки используются только для ключей, это регулярное выражение выполнит свою работу:
let str = "{“title”:\"this is a “test” example\"}"
let strFixed = str.replacingOccurrences(
of: #"“(.[^”]*)”:\"(.[^\"]*)\""#,
with: "\"$1\":\"$2\"",
options: .regularExpression
)
let json = try! JSONSerialization.jsonObject(with: strFixed.data(using: .utf8)!)
Если мы напечатаем json
, мы получим правильный результат:
{
title = "this is a \U201ctest\U201d example";
}
Объяснение
“(.[^”]*)”:\"(.[^\"]*)\"
------------------------
“(.[^”]*)” match everything between curly braces,
except the closing curling brace character
: separator between keys and values
\"(.[^\"]*)\" match everything between double quotes,
except the double quote character
\"$1\":\"$2\"
-------------
\"$1\" place the first captured group between double quotes
: separator between keys and values
\"$2\" place the second captured group between double quotes