开发者

How to encode this string to JSON?

I have this JSON string

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

which I construct in a low level way, so to speak.

How do I encode it using the JSON module?

Right now I开发者_StackOverflow encode 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;


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

Here are a couple of variants to encode 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;


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

The given error string:

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

is invalid as far as I know.


I don't know if the functionality was added after the responses, but you CAN encode a json string using perl, using the JSON module.

Using allow_nonref:

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

$enabled = $json->get_allow_nonref

If $enable is true (or missing), then the encode method can convert a non-reference into its corresponding string, number or null JSON value, which is an extension to RFC4627. Likewise, decode will accept those JSON values instead of croaking.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜