如何在javascript中将json objectId转换为其字符串表示
How to convert json objectId to its string representaion in javascript
我想将从 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)
}
相关文章:
- 如何使用JQuery在Javascript中转换字符串中的HTML元素
- 将JSON插入MongoDB中,自动转换字符串中的日期
- 以点表示法转换字符串以获取对象引用
- 在 JavaScript 中转换字符串 11/28/2014 11:00 AM 到现在
- 为什么在主干的字符串数组中转换字符串数组
- 如何简单地转换字符串
- AngularJS如何转换字符串“;yyyyMMdd”;迄今为止
- 如何防止htmlspecialchar(PHP)转换字符串中的整数
- 刷新Aurelia中的i18n转换字符串插值
- 发布时禁用转换字符串
- 转换字符串货币
- 在javascript ajax调用中转换字符串到数组
- 转换字符串包含时间到24小时的时间,我可以做数学与- jQuery
- IE javascript引擎在转换字符串到日期时呈现NaN
- 如何转换字符串“a,b,c,d……”成a.b (c, d . .);来执行
- 如何在javascript中转换字符串到日期格式
- 如何在嵌套数组中转换字符串数组
- 在javascript中转换字符串日期
- 转换字符串在印度格式的javascript
- Javascript转换字符串到数组的对象