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

JSON saving regex?

by iaw4 (Monk)
on Jan 27, 2012 at 00:59 UTC ( #950244=perlquestion: print w/replies, xml ) Need Help??
iaw4 has asked for the wisdom of the Perl Monks concerning the following question:

my data structure contains some regexs deep inside, and I am trying to convert this structure to json alas, I don't know how to convince JSON to play ball:
use JSON qw(-convert_blessed_universally); my $test = qr/^[\w\@\.]+$/; print to_json($test);
gives me an error
encountered object '(?^:^\w\@\.+$)', but neither allow_blessed nor convert_blessed settings are enabled
what is the proper syntax to get this going? advice appreciated.

Replies are listed 'Best First'.
Re: JSON saving regex?
by GrandFather (Sage) on Jan 27, 2012 at 02:32 UTC

    In essence you can't do that. $test contains a Perl regular expression object and JSON doesn't have an out-of-the-box way to deal with them.

    If you don't need to round trip the data, but are providing it for consumption elsewhere the allow_blessed function will suppresses the error, insert a 'null', and carry on:

    use strict; use warnings; use JSON qw(); my $test = {regex => qr/^[\w\@\.]+$/, str => "this is a string"}; my $json = JSON->new(); $json->allow_blessed(1); print $json->encode($test);


    {"str":"this is a string","regex":null}

    Update: and if you do want to round trip it with another Perl script then think about using YAML instead:

    use strict; use warnings; use YAML qw(); my $test = {regex => qr/\w+\W+(\w+)/, str => "this is a string"}; my $yamlStr = YAML::Dump($test); print "YAML: $yamlStr\n"; my $andBack = YAML::Load ($yamlStr); my ($secondWord) = $andBack->{str} =~ $andBack->{regex}; print "Second word is: $secondWord\n";


    YAML: --- regex: !!perl/regexp (?-xism:\w+\W+(\w+)) str: this is a string Second word is: is
    True laziness is hard work
Re: JSON saving regex?
by thargas (Deacon) on Jan 27, 2012 at 13:16 UTC

    The problem is that qr/.../ produces a Regexp object (try ref(qr/.../)).

    If you know where all the regexes are in your structure, you could convert them all to strings before calling to_json() on them.

    Or you can do:
    { package Regexp; sub TO_JSON { my $regex = shift; $regex = "$regex"; return $regex; } my $json = JSON->new->convert_blessed; print $json->encode(qr/.../);
    as documented in JSON

      Thanks for showing that this solution exists.

      (I hoped it would, but was too lazy to look it up :)

      Just one remark: I hope the OP doesn't expect that those RegExes always work in other languages than Perl.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://950244]
Approved by GrandFather
Front-paged by Corion
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (2)
As of 2018-05-24 05:17 GMT
Find Nodes?
    Voting Booth?