使用卷曲引号时将字符串JSON转换为Swift中的字典

问题描述 投票:2回答:1

我有一个字符串JSON,但是其中有花哨的弯引号,这使NSJSONSerialization失败。

let str = "{“title”:\"this is a “test” example\"}"

try! JSONSerialization.jsonObject(with: str.data(using: .utf8)!) // Error

title周围的引号是双引号,显然JSONSerialization无法处理它并失败。幼稚的方法是简单地将卷曲引用的所有实例替换为非卷曲的实例。这种方法的问题在于它将更改test周围的弯引号,不应更改! title周围的引号可以更改,但test周围的引号不能更改。

如何解决此问题?

swift quotes nsjsonserialization
1个回答
0
投票

如果仅将弯引号用于键,则此正则表达式将完成此工作:

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";
}
© www.soinside.com 2019 - 2024. All rights reserved.