如何解码JSON字符串?
问题描述:
在服务器端,我有2个哈希,我编码为JSON字符串,如此
On the server side do I have 2 hashes I encode into JSON strings like so
my $j = JSON->new;
$j = $j->utf8;
my $data;
$data->{users} = $j->encode(\%user_result);
$data->{owners} = $j->encode(\%owner_result);
$json_string = to_json($data);
print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json_string;
在客户端我有
$(document).ready(function(){
$('form').live('submit', function(){
$.ajax({
type: "GET",
url: "/cgi-bin/ajax_confirm.pl",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: $(this).serialize(),
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('div#create_result').text("responseText: " + XMLHttpRequest.responseText +
", textStatus: " + textStatus +
", errorThrown: " + errorThrown);
$('div#create_result').addClass("error");
},
success: function(result){
if (result.error) {
$('div#create_result').text("result.error: " + result.error);
$('div#create_result').addClass("error");
} else { // perl script says everything is okay
var users = result.users;
var owners = result.owners;
...
用户
包含
{"ss":"Sandra Schlichting","fn":"Full name"}
但它不是数组。当我使用 $。each()
时,它会一次占用角色。
but it is not an array. When I use $.each()
it takes on character at a time.
问题
如何将其变成数组,因此我可以使用
How do I turn it into an array, so I can use
function makeTable(users) {
var result = '<table>\n<tr><td>Initials</td><td>Full Name</td></tr>\n';
$.each(users, function(index, value) {
result += '<tr><td>' + index + '</td><td>' + value + '</td></tr>\n';
});
result += '</table>';
return (result);
}
应生成
Initials Full Name
ss Sandra Schlichting
fn Full name
答
你应该使用 http://api.jquery.com/jQuery.getJSON/ 。
还有$ .parseJSON()方法来解析字符串如果你想这样去json。
There is also $.parseJSON() method to parse string to json if you want to go that way.