in reply to malformed UTF-8 character in JSON string in perl
First of all,
is silly since it's effectivelydecode_json(encode_utf8($json))
from_json(decode_utf8(encode_utf8($json)))
That's why we told you should be using from_json.
use utf8; use JSON qw( from_json ); my $json = q({ "cat" : "text – abcd" }); my $data = from_json($json);
As for your new question, U+2013 EN DASH ("–") isn't found in ASCII's character set, so it can't be encoded using ASCII.
But unless your terminal uses ASCII, there's no reason to convert to ASCII. All you need to do is tell Perl what encoding your terminal expects. You can either encode explicitly, or you can use the "open" pragma as follows:
use open ':std', ':encoding(UTF-8)'; print($data->{cat}, "\n");
The whole script:
#!/usr/bin/perl use strict; use warnings; use utf8; # Source encoded using UTF-8. use open ':std', ':encoding(UTF-8)'; # Terminal expects UTF-8. use JSON qw( from_json ); my $json = q({ "cat" : "text – abcd" }); my $data = from_json($json); print($data->{cat}, "\n");
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: malformed UTF-8 character in JSON string in perl
by Yllar (Novice) on Aug 11, 2015 at 15:13 UTC | |
by ikegami (Patriarch) on Aug 11, 2015 at 21:13 UTC |