I'm using JSON::XS to generate an ld+json object. I'm not clear on what the correct way is to escape string literal values.

JSON::PP has an escape_slash() method. JSON::XS does not. But there is also a Cpanel::JSON::XS fork that does implement it.

Cpanel::JSON::XS includes this note:

According to the JSON Grammar, the forward slash character (U+002F) "/" need to be escaped. But by default strings are encoded without escaping slashes in all perl JSON encoders.

So what is best practice? Why doesn't JSON::XS offer the escape_slash() method? Is it a false sense of security? If so, what's the safest route? To escape all of the strings in the data structure before encoding to JSON?

It seems like having an escape option as part of the JSON encoding would be less error-prone. What are y'all doing?

This page talks about the problem and recommends using jsesc with Node: https://www.man42.net/blog/2016/12/safely-escape-user-data-in-a-script-tag/

What's the equivalent of jsesc for Perl?

Thanks!


In reply to JSON::XS and escaping literal strings by abelard12

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.