我想检查用户输入的文本是否是有效的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?
答案 0 :(得分:2)
你可以用字符串替换裸函数调用,类似这样
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)
答案 1 :(得分:0)
您所拥有的问题不是JSON验证之一,它与数据库是否实际上是ACCEPTS输入数据有关。您已经有了正确的想法来检查语法是否正确,但您必须通过mongo集合运行数据并检查是否存在任何错误。
查看MongoDB db.collection.explain()以验证它是否是有效的Mongo查询