I'm struggling with something that I thought would be very simple. I have a legacy system which sends data in JSON. The underlying data, which I can't change, uses HTML entities. I need to convert this to UTF8, because a receiving system can't handle the entities. I wrote a one-line test for this, which is failing, and I don't know why.

When I do the conversion on the text itself, it looks fine. When I do the conversion on the JSON, it also looks fine, but when I decode the JSON for the test, it seems to re-convert the UTF8 JSON elements into something wrong. A simple test case:

#!/usr/bin/env perl use strict; use warnings; use HTML::Entities; use Encode; use JSON::MaybeXS; my $original_string = "Eötvös Loránd University"; my $converted_string = encode_utf8( decode_entities($original_string) +); print "Original string: [$original_string]\n"; # shows the entities print "Converted string: [$converted_string]\n"; # shows the special c +haracters my $entities_json = '{"school":"Eötvös Loránd Uni +versity"}'; my $converted_json = encode_utf8(decode_entities($entities_json)); print "Original JSON: [$entities_json]\n"; # shows the entities print "Converted JSON: [$converted_json]\n"; # looks right: shows the +special characters my $decoded_json = decode_json($converted_json); print "School: " . $decoded_json->{'school'} . "\n"; # should be "Eötv +ös Loránd University" but is actually "�tv�s Lor&#65533 +;nd University", with the special characters messed up (N.B. Perlmonk +s is showing this incorrectly as well)
What is going on here? And, how am I supposed to convert my JSON-with-entities to something, well, correct?

In reply to Converting entities in JSON context 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.