Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upgrade safely from JSON 1 to JSON 2 wrt utf8 strings?

Tags:

json

utf-8

perl

We have a large code base that makes copious use of the JSON v1 API:

use JSON;
my $json = objToJson($data);
my $data = jsonToObj($json);

We would like to upgrade to JSON v2, so we can start using it in new code, and because we've been encountering other modules that depend on the v2 API.

However, if I have stored a utf8-string created by objToJson(), it will no longer be decoded in the same way by JSON::XS (which is what JSON v2 uses behind the scenes).

use JSON;
use JSON::XS;
use warnings;
use strict;

my $data    = ["\x{263a}b"];
my $encoded = JSON::objToJson($data);
print "different!\n"
  unless JSON::jsonToObj($encoded)->[0] eq JSON::XS::decode_json($encoded)->[0];
print "different!\n"
  unless JSON::jsonToObj($encoded)->[0] eq JSON::XS->new->decode($encoded)->[0];

Is there any way for us to upgrade to JSON v2, but still leave around the v1 API for backward compatibility with existing code?

like image 794
Jonathan Swartz Avatar asked Nov 13 '22 16:11

Jonathan Swartz


1 Answers

Modules should use a new name when they do drastic changes like that. In this case, the fact that JSON 2.x is mostly a wrapper for JSON::XS conveniently means that's kind what they did.

I recommend:

  1. Leave JSON 1.x installed.
  2. Install JSON::XS.
  3. At your leisure, convert from JSON 1.x to JSON::XS.
  4. It's now safe to upgrade to JSON 2.x if you want.
    1. Install JSON 2.x
    2. s/JSON::XS/JSON/g
like image 133
ikegami Avatar answered Dec 26 '22 22:12

ikegami