Search code examples
javascriptjsonnode.jsbson

How to create a JSON object from a BSON string which contains ISODate


I am trying to create a JSON object from a string which contains ISODate.

var teststring = '{ "_id" : "test001", "CreatedDate" : ISODate("2013-04-02T10:37:21.529Z") }';
console.log(JSON.parse(teststring));

Getting the ERROR:

undefined:1
{ "_id" : "test001", "CreatedDate" : ISODate("2013-04-02T10:37:21.529Z") }
                                     ^

Solution

  • To expand upon the answer by @user1896296

    var valid = teststring.replace("ISODate(", "").replace(")", "");
    

    is not very robust and shouldn't be used for production worthy code. Use a regular expression to do your replacement.

    var isoRegex = /ISODate\((".+?")\)/g;
    teststring = teststring.replace(isoRegex, function (match, parenGroup) {
        return parenGroup;
    });
    var parsedObj = JSON.parse(teststring);
    

    This will work correctly even in this situation:

    {
        "_id" : "test001",
        "RandomUserInput" : "Sometimes I like to say ISODate(\"2013-04-02T10:37:21.529Z\") in the body of my replies!",
        "CreatedDate" : ISODate("2013-04-02T10:37:21.529Z")
    }
    

    Since any double quotes inside the user's input must be escaped, the regular expression can't possibly match on user-supplied input.

    Furthermore, if you actually want to parse those fields into date objects, you could write a helper function like so:

    var isoRegex = /"([^"]+?)"\s*:\s*ISODate\((".+?")\)/g;
    function parseBson (bson) {
        var dateProps = [];
        bson = bson.replace(isoRegex, function (match, propName, dateStr) {
            dateProps.push(propName);
            return '"' + propName + '" : ' + dateStr;
        });
    
        var obj = JSON.parse(bson);
    
        for (var i in dateProps)
            obj[dateProps[i]] = new Date(obj[dateProps[i]]);
    
        return obj;
    }
    
    var parsedObj = parseBson(teststring);
    

    Note, this function would only work for top-level attributes. Trying to automatically convert nested properties would get tricky.