Confirm JSON from Mongo?

I want to check if the text the user enters is really JSON. I know that I can easily do this using something like this:

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

My problem is the JSON that comes from Mongo, which is wrapped in ObjectId , ISODate , ie:

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

This is not valid JSON. How can I validate JSON by assuming something like above?

+7
json javascript validation mongodb
source share
2 answers

you could replace the bare function call with strings, something like this

 function IsJsonLikeString(str) { str = str.replace(/(\w+)\("([^"]+)"\)/g, '"$1(\"$2\")"'); try { JSON.parse(str); } ... 

explanation 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) 
+2
source share

The problem you are facing is not JSON validation; it is related to whether the database ACCEPTS the input. You have the right idea to check the syntax is correct, but then you need to run the data through the mongo collection and check if there are any errors.

Check MongoDB db.collection.explain () to check if it is a valid Mongo request

0
source share

All Articles