2016-05-14 48 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()以驗證它是否是一個有效的蒙戈查詢