如何在javascript中将json objectId转换为其字符串表示形式

时间:2013-09-08 12:45:41

标签: javascript json mongodb bson objectid

我想将从REST mongodb API返回的bson ObjectId的json表示转换为string from:{“inc”:1365419770,“machine”: - 856505582,“timeSecond”:1375343587,“time”:1375343587000,“new”:false};

至:51fa13e3ccf2c3125162a6fa

在客户端,因此它将使用路径参数调用其他API。

1 个答案:

答案 0 :(得分:1)

我刚开发它,以防其他人正在寻找相同的功能。

var ObjectIdStr = function (hexstr) {
    this.timestamp  ;
    this.machine    ;
    this.increment  ;

    if (this.__proto__.constructor !== ObjectIdStr) {
        return new ObjectIdStr(hexstr);
    }

    var isValid = function( s ){
        if ( s == null )
            return false;
        len = s.length;
        if ( len != 24 )
            return false;
        for ( i=0; i<len; i++ ){
            c = s.charAt(i);
            if ( c >= '0' && c <= '9' )
                continue;
            if ( c >= 'a' && c <= 'f' )
                continue;
            if ( c >= 'A' && c <= 'F' )
                continue;
            return false;
        }
        return true;

    }

    var fromHex = function(hex){
        hex = parseInt(hex, 16);
        if (hex > 0x80000000) {
            hex = hex - 0xFFFFFFFF - 1;
        }      
        return hex;
    }

    if ( ! isValid( hexstr ) )
        throw "invalid ObjectId [" + s + "]" ;

    this.timestamp  = fromHex(hexstr.substring(0,8));
    this.machine    = fromHex(hexstr.substring(8,16));
    this.increment  = parseInt( hexstr.substring(16,24) , 16);  
}

var ObjectId = function (json) {
    this.timestamp  = json.timeSecond;
    this.machine    = json.machine;
    this.increment  = json.inc;

    if (this.__proto__.constructor !== ObjectId) {
        return new ObjectId(json);
    }
    var hex = function(number){
        if (number < 0) {
            number = 0xFFFFFFFF + number + 1;
        }
        return number.toString(16).toLowerCase();
    }

    this.toString = function () {       
        var timestamp   =   hex(this.timestamp);
        var machine     =   hex(this.machine);
        var increment   =   hex(this.increment);
        return '00000000'.substr(0, 6 - timestamp.length) + timestamp +
               '00000000'.substr(0, 6 - machine.length)   + machine   +
               '00000000'.substr(0, 6 - increment.length) + increment ;
    };
};


function testme(){
    var objJson = {"inc":1365419770,"machine":-856505582,"timeSecond":1375343587,"time":1375343587000,"new":false};
    $("#ObjIdStr").html(ObjectId(objJson).toString());
    obj = ObjectIdStr("51fa13e3ccf2c3125162a6fa")
    $("#out").html( obj.increment + " " + obj.machine + " " + obj.timestamp)
}