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

How to convert json objectId to its string representaion in javascript

本文关键字:转换 字符串 表示 objectId json javascript 中将      更新时间:2023-09-26

我想将从 REST mongodb API 返回的 bson ObjectId 的 json 表示转换为字符串from: {"inc":1365419770,"machine":-856505582,"timesecond":1375343587,"time":1375343587000,"new":false};

收件人:51FA13E3CCF2C3125162A6FA

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

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

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)
}