将JSON插入MongoDB中,自动转换字符串中的日期
Inserting JSON into MongoDB converting dates from strings automatically
我有一些对象使用键updated_at
和created_at
,它们具有类似2012-08-29T16:04:34-04:00
的字符串时间戳。我正在将其插入MongoDB中。问题是,每个对象都可以有数量可变的updated_at
和created_at
实例(它们在中的数组中)。有没有任何代码可以用来在数组中搜索updated_at
和created_at
,并用$.created_at = new Date($.created_at)
替换这些值?
{
"name":"thomas",
"created_at":"2012-08-29T16:04:34-04:00",
"updated_at":"2012-08-29T16:04:34-04:00",
"logs":[
{
"something":"something",
"created_at":"2012-08-29T16:04:34-04:00",
},
{
"something":"something",
"created_at":"2012-08-29T16:04:34-04:00",
},
]
}
至
{
"name":"thomas",
"created_at":new Date("2012-08-29T16:04:34-04:00"),
"updated_at":new Date("2012-08-29T16:04:34-04:00"),
"logs":[
{
"something":"something",
"created_at":new Date("2012-08-29T16:04:34-04:00"),
},
{
"something":"something",
"created_at":new Date("2012-08-29T16:04:34-04:00"),
},
]
}
// store your data object in x
x = {
"name":"thomas",
"created_at":"2012-08-29T16:04:34-04:00",
"updated_at":"2012-08-29T16:04:34-04:00",
"logs":[
{
"something":"something",
"created_at":"2012-08-29T16:04:34-04:00",
},
{
"something":"something",
"created_at":"2012-08-29T16:04:34-04:00",
},
]
}
// create a traversal function to recurse
function traverse(o) {
// loop through object
for (i in o) {
// if it is a matched key (current regex matches created_at or updated_at)
// parse the item as a date, and re-store object
if(i.match(/(cre|upd)ated_at/)){
o[i] = new Date(o[i])
}
// if the key we are looking at is an object, then recurse!
if (typeof(o[i])=="object") {
traverse(o[i])
}
}
}
// fire it up!
traverse(x)
// check the results
console.dir(x)
// store your data object in x
x = {
"name":"thomas",
"created_at":"2012-08-29T16:04:34-04:00",
"updated_at":"2012-08-29T16:04:34-04:00",
"logs":[
{
"something":"something",
"created_at":"2012-08-29T16:04:34-04:00",
},
{
"something":"something",
"created_at":"2012-08-29T16:04:34-04:00",
},
]
}
// loop through each element of the logs array
for(y in x.logs){
// modify the `created_at` value of the y-th element
// by wrapping with the desired string
x.logs[y].created_at = "new Date(" + x.logs[y].created_at + ")"
}
// check the final format of the object
console.dir(x)
注意事项:
该对象存储一个包含new Date ...
ammendment的字符串-要存储操作的结果,您需要将修改行调整为…
x.logs[y].created_at = new Date( x.logs[y].created_at )
相关文章:
- 如何使用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转换字符串到数组的对象