Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate JSON from Mongo?

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?

like image 441
KJ3 Avatar asked May 14 '16 18:05

KJ3


1 Answers

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)
like image 84
Aprillion Avatar answered Nov 14 '22 21:11

Aprillion