3

All,

I'm using the JSON Perl module to encode JSON.

I'd like the resulting JSON to include lines like this:

{
   "startDate": new Date(2010,11,15,0,0),
   "aString"  : "String Data",
   "aNumber"  : 1234
}

In order to create that, I have a Perl HASHREF like this:

{
   startDate => SEE BELOW,
   aString   => "String Data",
   aNumber   => 1234,
}

Here's my problem: I can't figure out how to coerce the JSON module into printing unquoted strings, so that I can include my new Date(...) instantiation call. I've tried creating a Perl module with a TO_JSON method, but the output still gets quoted.

Does anybody out there have any suggestions on how I can encourage JSON to print unquoted strings?

Dancrumb
  • 26,597
  • 10
  • 74
  • 130

3 Answers3

7

JSON is not meant to encode objects like that. It encodes simple data structures like arrays and hashes. If you then want to use that deserialized data to populate a blessed object, you need to add another layer on top.

For Moose objects, the plugin MooseX::Storage is built for expressly this purpose.

Ether
  • 53,118
  • 13
  • 86
  • 159
  • @Bipedal: MooseX::Storage is set up to use JSON; if you're asking about something else, hop on to irc.perl.org #moose and we can help you find a solution. – Ether Nov 16 '10 at 01:13
3

What you want is invalid in JSON. See http://www.json.org/ for what is an valid value in JSON. I'd return the date as an array and then use that in you js handler to create the Date object.

jira
  • 3,890
  • 3
  • 22
  • 32
  • Thanks. I'm using the Simile Timeline at [http://code.google.com/p/simile-widgets/wiki/Timeline_EventSourceJSON_jsDate]. When I reread it, I noticed the 'invalid JSON' comment... I'll rethink my approach. Thanks – Dancrumb Nov 15 '10 at 20:16
2

Perhaps you should rethink your approach to this problem, say, by leaving the JSON module alone but post-processing its output? For example, come up with some convention to show that the receiver should do something special with the input:

{
   "startDate": "EVAL:new Date(2010,11,15,0,0)",
   "aString"  : "String Data",
   "aNumber"  : 1234
}

Let the receiver (Perl? JavaScript?) look for hash values that start with the keyword "EVAL:" and perform further processing on that value.

mob
  • 117,087
  • 18
  • 149
  • 283