简体   繁体   English

如何从JSON数据获取Date对象

[英]How to get a Date object from json data

I am just trying to parse a Json document with a field Date like this: ´ death':Date('2007-03-17T04:00:00Z') using 我只是想使用以下字段“日期”解析Json文档:“ death”:Date('2007-03-17T04:00:00Z')使用

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

There is an exception when the value Date is encountered. 遇到日期值时会发生异常。 Any help? 有什么帮助吗?

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. 可能有人在MongoDB Shell中运行了某些东西,并将控制台输出重定向到文件。 That is basically "doing it wrong". 这基本上是“做错了”。

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. 有一个称为MongoDB扩展JSON的概念,实际上已经在其他几个领域中得到了采用,特别是EJSON项目。此操作要尝试确保所有导出的JSON都将“类型”信息保持为BSON类型标识符(或其他对象类型,以达到EJSON的目的),以便类似的“扩展JSON”解析器可以将对象“重构”为预期的形式。

For a "date" object, the intented JSON representation is this: 对于“日期”对象,意图的JSON表示形式是这样的:

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

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. 由于com.mongodb.util.JSON.parse 通过扩展JSON规范的知识启用的,因此任何此类JSON结构都将导致从解析的数据构造正确的date对象。

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

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

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. 显然,此处的“最佳”操作是修复数据的“导出”源,以便它以正确的扩展方式将此日期解析为JSON。 Then the parser you are using will do the right thing. 然后,您使用的解析器将做正确的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM