2016-05-14 43 views
7

我想检查用户输入的文本是否有效JSON。我知道我可以轻松地用这样的事情:验证Mongo的JSON?

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

我的问题是与来自蒙戈,它被包裹在ObjectIdISODate JSON,即:

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

这是无效的JSON。如何在验证JSON的同时允许上述类似内容?

回答

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) 
+0

这绝对不会把戏!我做的唯一的调整是'''$ 1(\“$ 2 \”)“'',我在$ 2''”$ 1(\'$ 2 \')“'''周围放置单引号,因此它显示为”“ ObjectId('1234')“'而不是''ObjectId(”1234“)”',其中的引号会自行转义。 – KJ3

0

你就会有这个问题不是JSON验证的一个,它的与数据库是否实际接受输入数据有关。您有正确的想法来检查语法是否正确,但是您必须通过mongo集合运行数据并检查是否有任何错误。

退房MongoDB db.collection.explain()以验证它是否是一个有效的蒙戈查询