I can't really tell if what you want is sane, but I found the documentation of JSON::XS to be fairly explicit. If the convert_blessed option is set and an object has a TO_JSON method, that method will be called to convert the object to a string (or whatever).

So, "just" add a TO_JSON method to the Regexp namespace and you can serialize your regular expressions as strings.

#!perl -w use strict; use JSON::XS 'encode_json'; print encode_json({foo=>'bar'}); my $j=JSON::XS->new;$j->convert_blessed(1) print $j->encode({foo=>qr/bar/}); sub Regexp::TO_JSON{qq($_[0])}"

Update:

After discussion of the topic with choroba, I have to add that it is likely a far better approach to explicitly convert your regular expressions to strings manually. As you are generating the data structure, you should also know at which locations there are regular expressions. Convert these to strings.

Also, I want to question the choice of JSON as a serialization format. If you want speed, there are better approaches that allow serializing regular expressions, like Sereal. If you want something human-editable, YAML at least allows comments, which JSON doesn't allow.


In reply to Re: Freezing a regular expression qr() by Corion
in thread Freezing a regular expression qr() by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.