0

I'm using PostgreSQL 9.3 and looking for a way to incorporate TIMESTAMPTZ as true JavaScript date objects.

I understand that JavaScript does not offer Date literal notation, so I was thinking

'{ "key" : new Date(datevalue) }'::JSON

would do the trick.

The problem is that I get the error: Token "new" is invalid.

Is it possible for me to update the Postgres JSON parser?

Maybe there is some other way I can get a bit more datatype consistency as I pass data between the front and back end... any thoughts?

1 Answer 1

1

That doesn't make any sense. JSON doesn't support atomic elements other than string /number / boolean. See the spec for details.

One of the main purposes of the format is to be (machine) language independent so having embedded Javascript Date objects (or Regex or Window or any other) makes no sense. What would it mean when you load that JSON in e.g. C++ - how would you call the methods on the embedded Date object?

A timestamp is text. Anything other than a number or a boolean is text. If that's not good enough for you then you either need to layer some more meaning on top of JSON or pick a different format.

Sign up to request clarification or add additional context in comments.

3 Comments

I disagree. A timestamp should not be text, it should be an object and if it can't be, it would have to be a number. JSON is more than just "string / number / boolean". From the docs: A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. You're correct, imbedding a function call into JSON may create problems (if I were to send that function to a language that can't call it). My original question still stands, how can I update the Postgres JSON parser to allow the Date constructor?
I fully support your right to be wrong, and I'm afraid this time you are. Re-read the specs. A JSON "object" is nothing more than what Perl calls a hash and PHP an associative array. JSON cannot contain functions in any form because they are not strings, numbers, boolean or null. To modify PostgreSQL's JSON parser, just download the source-code open a text editor and edit some C (start with files with json in their name). It won't be a JSON parser any more though, will it? You'll need a different name for the format and you'll be the only one who uses it.
A timestamp should not be text, Ideally I would agree. Unfortunately the spec doesn't agree.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.