Is there a way to encode object constructors with the JSON Perl Module?
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 开发者_Go百科how I can encourage JSON to print unquoted strings?
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.
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.
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.
精彩评论