Navigation Menu

Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to convert bool values to 1 and 0? #103

Closed
bessarabov opened this issue Nov 7, 2016 · 2 comments
Closed

How to convert bool values to 1 and 0? #103

bessarabov opened this issue Nov 7, 2016 · 2 comments

Comments

@bessarabov
Copy link
Contributor

bessarabov commented Nov 7, 2016

Here is the code:

use JSON::PP;

use Data::Printer filters => {
    'JSON::PP::Boolean' => sub { $_[0] ? 1 : 0 }
} ;

my $data = decode_json '{
    "a":true,
    "b":false,
    "c":true
}';

p $data;

it outputs:

\ {
    a   1,
    b   0,
    c   var{a}
}

How can I make it to output

\ {
    a   1,
    b   0,
    c   1
}

?

PS this question was inspired by https://www.jwz.org/blog/2016/10/death-to-jsonppboolean/ (and a tweet https://twitter.com/jwz/status/792831646525378560 )

@dur-randir
Copy link
Contributor

dur-randir commented Nov 7, 2016

This can be achieved with more-or-less public interface using external filters:

package Data::Printer::Filter::JPB;

use Data::Printer::Filter;

filter 'JSON::PP::Boolean', sub {
    $_[0] ? 1 : 0
}, {show_repeated => 1};
use JSON::PP;

use Data::Printer filters => {
    -external => [ 'JPB' ],
};

my $data = decode_json '{
    "a":true,
    "b":false,
    "c":true
}';

p $data;

For inline filters, there's no easy way except for hacking into internal options:

p($data, _seen_override => {'JSON::PP::Boolean' => 1} );

@bessarabov
Copy link
Contributor Author

@dur-randir thank you! This is exactly what i was looking for.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants