I want to check if the text a user enters is valid JSON. I know I can easily do that using something like this:
function IsJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
My problem is with JSON that comes from Mongo, which is wrapped in ObjectId
, ISODate
, i.e.:
{
"_id" : ObjectId("5733b42c66beadec3cbcb9a4"),
"date" : ISODate("2016-05-11T22:37:32.341Z"),
"name" : "KJ"
}
This is not valid JSON. How could I go about validating JSON while allowing something like the above?
you could replace the naked function calls with strings, something like this
function IsJsonLikeString(str) {
str = str.replace(/(\w+)\("([^"]+)"\)/g, '"$1(\"$2\")"');
try {
JSON.parse(str);
} ...
explanation from 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With