Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re^3: Json::PP data error

by davido (Cardinal)
on Dec 24, 2019 at 04:48 UTC ( #11110578=note: print w/replies, xml ) Need Help??


in reply to Re^2: Json::PP data error
in thread Json::PP data error

Date::Simple uses overload to cause the Date::Simple object to act appropriately according to the operators it's used with. So where the object, if not using overload, would stringify as something like Date::Simple=HASH(0x556b93cb2780), because stringification has been overloaded, the handler converts it to a date stamp.

However, JSON::PP uses ref to determine how to handle the structure being JSONified. If ref returns a hash, then a JSON hash is created. If ref returns an array, then a JSON array is created. If ref returns an object of some type, then JSON::PP looks for a TO_JSON method in that object's class for the object to know how to JSON encode it. If there isn't one, you get the error you've seen. It's just an impedance mismatch, and can be dealt with by forcing the object to the format you need. In this case wrapping it in quotes will use the overloaded stringification, which does what you want.

Alternatively you could subclass Date::Simple and provide your own TO_JSON method that munges the object as you wish. Something like this:

package Date::Simple::JSONable; use parent 'Date::Simple'; sub TO_JSON { my $self = shift; return "$self"; } 1;

The problem with this, though, is if the Date::Simple object is created by another library. That won't give you an easy opportunity to prevent that library from just creating a Date::Simple object rather than your Date::Simple::JSONable. If that's the case you now find yourself needing to subclass that library. And that's probably too much work.

Another alternative is to provide your own TO_JSON method to Date::Simple:

package main; use strict; use warnings; use Module::That::Instantiates::A::Date::Simple; sub Date::Simple::TO_JSON { return "$_[0]"; } # The rest of your code here...

Now you're just injecting a TO_JSON method into Date::Simple so that when JSON::PP needs one, it's there.


Dave

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11110578]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (7)
As of 2020-05-30 12:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If programming languages were movie genres, Perl would be:















    Results (171 votes). Check out past polls.

    Notices?