Ganesh Ganesh - 7 months ago 47
Perl Question

decode_json error getting error because of encoding issue

I'm getting an error executing the following code:

use JSON;
use Encode qw( encode decode encode_utf8 decode_utf8);
my $arr_features_json = '[{"family":"1","id":107000,"unit":"","parent_id":"0","cast":"2","search_values_range":"1,2,3,4,5,6,7,8,9,10,11,12","category_id":"29","type":"2","position":"3","name":"Número de habitaciones","code":"numberofrooms","locales":"4","flags":"1"}]';
$arr_features_json = decode_json( $arr_features_json );


The following is the error I get:


malformed UTF-8 character in JSON string, at character offset 169 (before "\x{fffd} de habitaci...") at test.pl line 13.


decode_json
is issuing the error because of the
ú
character in the json, so I want to convert this character to
\u00fa
. How can I do that?

Answer

The error says that string you are trying to process is not an UTF-8 or faulty UTF-8 string. So, you need to convert it to UTF-8 string using encode_utf8 before decoding it to json.

use JSON;
use Data::Dumper;
use Encode qw( encode decode encode_utf8 decode_utf8);

my $arr_features_json = '[{"family":"1","id":107000,"unit":"","parent_id":"0","cast":"2","search_values_range":"1,2,3,4,5,6,7,8,9,10,11,12","category_id":"29","type":"2","position":"3","name":"Número de habitaciones","code":"numberofrooms","locales":"4","flags":"1"}]';
my $arr_features = decode_json( encode_utf8($arr_features_json) );

print Dumper($arr_features);

Probably you should check a this article to know difference between UTF-8 strings and character strings.

Comments