在做一些 HTML 抓取时,我遇到了这种类型的 JS 对象:
[{
key1: "Hello",
key2: "There",
}, {
key1: "Goodbye",
key2: "See you",
},]
请注意,键未包含在 ""
之间,因此它不是有效的 JSON 字符串。因此,我无法在不进行一些处理的情况下将其解析为 JSON/NSArray/NSDictionary
。
是否存在可以将这种字符串转换为适当的 Objective-C 对象的任何库/内置函数?
最佳答案
我终于在this Dimmzy's blog post 上找到了解决方案| (感谢this almost identical question)。使用此函数从脏字符串中获取干净的 JSON 字符串:
+ (NSString *)fixJSON:(NSString *)s {
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:@"[{,]\\s*(\\w+)\\s*:"
options:0
error:NULL];
NSMutableString *b = [NSMutableString stringWithCapacity:([s length] * 1.1)];
__block NSUInteger offset = 0;
[regexp enumerateMatchesInString:s
options:0
range:NSMakeRange(0, [s length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
NSRange r = [result rangeAtIndex:1];
[b appendString:[s substringWithRange:NSMakeRange(offset, r.location - offset)]];
[b appendString:@"\""];
[b appendString:[s substringWithRange:r]];
[b appendString:@"\""];
offset = r.location + r.length;
}];
[b appendString:[s substringWithRange:NSMakeRange(offset, [s length] - offset)]];
return b;
}
关于javascript - 使用 Objective-C 解析包含未被 ""包围的键的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11818239/