如何解码JSON字符串? [英] How to decode a JSON string?

查看:87
本文介绍了如何解码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.

这篇关于如何解码JSON字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆