我想检查用户输入的文本是否是有效的 JSON。我知道我可以使用以下方法轻松做到这一点:
function IsJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
我的问题是来自 Mongo 的 JSON,它包含在 ObjectId
、ISODate
中,即:
{
"_id" : ObjectId("5733b42c66beadec3cbcb9a4"),
"date" : ISODate("2016-05-11T22:37:32.341Z"),
"name" : "KJ"
}
这不是有效的 JSON。在允许上述内容的同时如何验证 JSON?
最佳答案
你可以用字符串替换裸函数调用,像这样
function IsJsonLikeString(str) {
str = str.replace(/(\w+)\("([^"]+)"\)/g, '"$1(\"$2\")"');
try {
JSON.parse(str);
} ...
来自 https://regex101.com/r/fW7iH4/#javascript 的解释:
/(\w+)\("([^"]+)"\)/g
1st Capturing group (\w+)
\w+ match any word character [a-zA-Z0-9_]
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
\( matches the character ( literally
" matches the characters " literally
2nd Capturing group ([^"]+)
[^"]+ match a single character not present in the list below
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
" a single character in the list " literally (case sensitive)
" matches the characters " literally
\) matches the character ) literally
g modifier: global. All matches (don't return on first match)
关于javascript - 验证来自 Mongo 的 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37230282/