ferrito
ferrito

Reputation: 341

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

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

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

Upvotes: 1

Views: 614

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151122

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".

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.

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

{ "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.

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. 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. Then the parser you are using will do the right thing.

Upvotes: 2

Related Questions