How to encode this string in JSON?

I have this JSON string

$json_string = qq{{"error" : "User $user doesn't exist."}};

which I build on a low level, so to speak.

How to encode it using the JSON module?

Right now i am encoding hashes like this

use JSON;
my $json_string;

my $json = JSON->new;
$json = $json->utf8;

my $data;
$data->{users}  = $json->encode(\%user_result);
$data->{owners} = $json->encode(\%owner_result);
$json_string    = to_json($data);

print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json_string;
+3
source share
3 answers

Ratna is right - you cannot encode a simple string (unless you put it in a list or hash)

Here are a few options for encoding your string:

use strict;
use warnings;
use JSON;

my $user = "Johnny";

my $json_string = { error_message => qq{{"error" : "User $user doesn't exist."}} } ;
$json_string    = to_json($json_string);
print "$json_string\n";

#i think below is what you are looking for
$json_string = { error => qq{"User $user doesn't exist."} };
$json_string    = to_json($json_string);
print $json_string;
+6
source

JSON must be either {key:value}or[element]

The specified error string:

qq{{"error" : "User $user doesn't exist."}}
As I know,

is invalid.

+1
source

, ​​ , json perl, JSON.

allow_nonref:

$json = $json->allow_nonref([$enable])

$enabled = $json->get_allow_nonref

$enable ( ), non-reference , JSON , RFC4627. , JSON .

Code and quote from https://metacpan.org/pod/release/MAKAMAKA/JSON-2.90/lib/JSON.pm#allow_nonref

+1
source

All Articles