Validate JSON from Mongo?

Validate JSON from Mongo?

本文关键字:Mongo from JSON Validate      更新时间:2023-09-26

我想检查用户输入的文本是否是有效的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?

您可以用字符串替换裸函数调用,类似于以下

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)

您将遇到的问题不是JSON验证问题,而是与数据库是否真的接受输入数据有关。检查语法是否正确是正确的想法,但您必须通过mongo集合运行数据,并检查是否存在任何错误。

查看MongoDB db.collection.explain()以验证它是否是有效的Mongo查询