我有一个有效的JSON字符串,如下所示: - DEMO
[
{
"field":"Name",
"rules":[
{
"Regex":"\\S",
"ValidationMessage":" Name cannot be blank."
},
{
"Regex":"^.{1,50}$",
"ValidationMessage":"Length should not exceeds 50 characters."
}
]
},
{
"field":"Abbreviation",
"rules":[
{
"Regex":"\\S",
"ValidationMessage":" Abbreviation cannot be blank."
},
{
"Regex":"^.{1,15}$",
"ValidationMessage":"Length should not exceeds 15 characters."
}
]
},
{
"field":"PhoneNumber",
"rules":[
{
"Regex":"\\S",
"ValidationMessage":"Phone Number cannot be blank."
},
{
"Regex":"^\\d{10}$",
"ValidationMessage":"Length must be 10 digits"
}
]
},
{
"field":"SelectedCampus",
"rules":[
{
"Regex":"\\S",
"ValidationMessage":"Please st Serviced Campus"
}
]
}
]
当我执行JSON.parse时,它会抛出错误: -
Uncaught SyntaxError: Unexpected token S
答案 0 :(得分:5)
将我的评论作为答案发布:在使用JSON.parse(..)
解析之前,您需要双重转义JSON字符串。
让我们拿一个像\\S
这样的字符串。它由两个字符组成:'\\', 'S'
。
JSON.parse("...\\S...")
认为这是一个反斜杠,并且在它之后需要一个'n','r','t'(或其他转义字符)。它既不期望S
,也不期望d
。因此,你得到了这个错误。
要解决此问题,您需要双重转义JSON字符串。喜欢:\\\\S
& \\\\d
。