我有这个 JSON 字符串
$json_string = qq{{"error" : "User $user doesn't exist."}};
可以这么说,我是以低级方式构建的。
如何使用 JSON 模块对其进行编码?
现在我像这样编码哈希
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 是对的——你不能编码一个简单的字符串(除非你把它放在一个列表或散列中)
这里有几个变体来编码你的字符串:
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;
关于perl - 如何将此字符串编码为 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6121727/