来自Mongo的JSON数据如何验证?

8

我希望检查用户输入的文本是否是有效的JSON格式。我知道可以使用类似以下代码的方式来实现:

function IsJsonString(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

我的问题出在来自Mongo的JSON数据上,其中包含了ObjectIdISODate,例如:

{
    "_id" : ObjectId("5733b42c66beadec3cbcb9a4"),
    "date" : ISODate("2016-05-11T22:37:32.341Z"),
    "name" : "KJ"
}

这不是有效的JSON格式。如果想要允许类似上述内容,该怎么验证JSON格式呢?

2个回答

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(\"$2\")"'中的$2用单引号括起来,变成了'"$1(\'$2\')"',这样它就会显示为"ObjectId('1234')", 而不是"ObjectId("1234")", 其中引号会自己转义。 - KJ3

0
你将会遇到的问题不是 JSON 验证的问题,而是与数据库是否实际接受输入数据有关。你已经有了正确的想法来检查语法是否正确,但是你还需要通过 MongoDB 集合运行数据并检查是否存在任何错误。
请查看 MongoDB db.collection.explain() 来验证它是否是有效的 Mongo 查询。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接