如何从JSON数据获取Date对象 [英] How to get a Date object from json data

查看:753
本文介绍了如何从JSON数据获取Date对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想用以下字段Date解析一个Json文档: ´death':Date('2007-03-17T04:00:00Z')使用

I am just trying to parse a Json document with a field Date like this: ´ death':Date('2007-03-17T04:00:00Z') using

com.mongodb.util.JSON.parse(document)

遇到值Date时会发生异常.有帮助吗?

There is an exception when the value Date is encountered. Any help?

推荐答案

此处的关键是导出数据的所有操作都做错了.可能有人在MongoDB Shell中运行了某些东西,并将控制台输出重定向到文件.这基本上是做错了".

The key here is whatever has exported the data has done it wrong. Possibly someone has run something from the MongoDB shell and redirecting console output to a file. That is basically "doing it wrong".

有一个名为 MongoDB扩展JSON 的概念,实际上是在其他几个领域中获得的,尤其是 EJSON项目.这样做的目的是确保所有导出的JSON都将类型"信息维护为BSON类型标识符(或其他对象类型,以EJSON的目的),以便类似的扩展JSON"解析器可以重构"反对它的预期形式.

There is a concept called MongoDB Extended JSON and has in fact been picked up in a few other areas, notably the EJSON project.What this tries to do is make sure that any exported JSON maintains "type" information to the BSON type identifier ( or other Object Type, in the purpose of EJSON ) so that a similar "extended JSON" parser can "re-construct" the object to it's intended form.

对于日期"对象,意图的JSON表示形式是这样:

For a "date" object, the intented JSON representation is this:

{ "death": { "$date": "2007-03-17T04:00:00Z" } }

由于com.mongodb.util.JSON.parse 已启用,并且已了解扩展JSON规范,因此任何此类JSON结构都将导致从解析的数据构造正确的日期对象.

Since com.mongodb.util.JSON.parse is enabled with knowledge of the Extended JSON spec, then any such JSON contruct will result in a correct date object being constructed from the parsed data.

因此,您现在所拥有的只是一个字符串".实际上,如果不是这样引用":

So what you have right now is just a "string". In fact, if it is not "quoted" like this:

´ { "death" : "Date('2007-03-17T04:00:00Z')" }

然后,它实际上甚至不是有效的JSON,甚至在基本的JSON解析器都不会出错之前,甚至需要将其处理为正确的格式.无论如何,结果仍然只是一个字符串",因此您需要使正则表达式与数字数据匹配,然后将其传递给日期对象构造.

Then it is not in fact even valid JSON and would even need to be manipulated to a correct form before even a basic JSON parser would not error. At any rate, the result is just a "string" still, so you would need to make a regex match for the numerical data, then pass that to a date object construct.

很显然,这里要做的最好"的事情是修复数据的导出"源,以便它以正确的扩展方式将此日期解析为JSON.然后,您使用的解析器将做正确的事.

Clearly the "best" thing to do here is to fix the "export" source of the data so that it is doing this date parsing to JSON in the correct extended way. Then the parser you are using will do the right thing.

这篇关于如何从JSON数据获取Date对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆