user3285371
user3285371

Reputation: 53

How can I parse JSON string with new Date() and get a Date property in the object?

Does anyone know how can I get MyDate property with an actual Date object after parsing?

var myObject = JSON.parse('{ "MyDate" : new Date ("2013-12-13"), "Test" : "TestString"}');

I have a file with thousands of records in JSON and I'm importing it with NodeJS

var content = require('./content.json');

It would be awesome if someone knows a trick like special quotation marks or something.

In both cases I get this exception:

SyntaxError: Unexpected token e
    at Object.parse (native)
    at repl:1:6
    at REPLServer.self.eval (repl.js:110:21)
    at repl.js:249:20
    at REPLServer.self.eval (repl.js:122:7)
    at Interface. (repl.js:239:12)
    at Interface.EventEmitter.emit (events.js:95:17)
    at Interface._onLine (readline.js:202:10)
    at Interface._line (readline.js:531:8)
    at Interface._ttyWrite (readline.js:760:14)

Upvotes: 2

Views: 1532

Answers (3)

user3285371
user3285371

Reputation: 53

As the Wikipedia says, JSON supports some JavaScript native datatypes and some others not:

http://en.wikipedia.org/wiki/JSON#Unsupported_native_data_types

So I can't do what I want in the way that I want but it's not so important. I can use strings and later somewhere format it.

Thank you for your help!

Upvotes: 0

alex
alex

Reputation: 12275

I'm curious, where is that JSON is coming from? There is no standard to represent dates, so such extensions might be interesting.

Anyway, this is not a classic JSON. There are dozens of different JSON flavors, but it doesn't look like anything I know of. It doesn't mean that your format is bad, but it does mean that standard JSON.parse will not work here.

However, you can parse it using YAML parser, in which case that Date will be represented as a string which you can replace later.

This is how you can deal with this format:

var YAML = require('js-yaml')
var object = YAML.safeLoad('{ "MyDate" : new Date ("2013-12-13"), "Test" : "TestString"}')

function parse_dates(v) {
  if (typeof(v) === 'object') {
     for (var i in object) {
        v[i] = parse_dates(v[i])
     }
  } else if (typeof(v) === 'string') {
     var m = v.match(/^new Date\s*\(["'](.*)["']\)$/)
     if (m != null) {
        return new Date(m[1])
     }
  }
  return v
}

console.log(parse_dates(object))

Result:

$ TZ=UTC node test.js 
{ MyDate: Fri Dec 13 2013 00:00:00 GMT+0000 (UTC),
  Test: 'TestString' }

Upvotes: 1

CodeViking
CodeViking

Reputation: 206

Just do this

var myObject = JSON.parse('{ "MyDate" : "'+new Date ("2013-12-13")+'", "Test" : "TestString"}');

Upvotes: 0

Related Questions