简体   繁体   中英

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)

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

做这个

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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