javascript - 验证来自 Mongo 的 JSON?

标签 javascript json mongodb validation

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

关于javascript - 验证来自 Mongo 的 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37230282/

相关文章:

javascript - Angular 服务/ Controller 不返回 promise ?

javascript - 需要一个 JS 日期库。 DateJS 自 2007-2008 年左右以来就没有更新过。红旗?

javascript - Jquery 在解析时将巨大的数组拆分为许多新的回调

json - 无法从帖子请求中解析 JSON

mysql - 如何跨多个服务器nodejs和socket.io存储socket.id

javascript - 将 native javascript 对象与 jQuery 进行比较

javascript - 如何让这个 Javascript 函数正确迭代?

java - 如何在java中获取没有字段名的jsonArray的值?

python - 在ming中创建连接之前声明模型

javascript - Meteor mongo插入独特的文档