How to decode a JSON string?

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;

On the client side I have


    $('form').live('submit', function(){

        type: "GET",
        url: "/cgi-bin/",
        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);

        success: function(result){
        if (result.error) {
            $('div#create_result').text("result.error: " + result.error);
        } else { // perl script says everything is okay

            var users  = result.users;
            var owners = result.owners;

users contains

{"ss":"Sandra Schlichting","fn":"Full name"}

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);

which should produce

Initials    Full Name
ss  Sandra Schlichting
fn  Full name



You should use jQuery.getJSON() as mentioned at

There is also $.parseJSON() method to parse string to json if you want to go that way.


You don't need to turn it into an array. According to the jQuery.each() documentation it takes both arrays or objects and JSON is a subset of the object literal notation of JavaScript.

Edit: Here's an example:


You can use the JSON parser created by douglas crockford:

include the json2.js in your page, the you can do:

var object = JSON.parse(string);

Then you can use it as an array.


you can use for in statement

var index = 0;
for(user in users){
  result += '<tr><td>' + index + '</td><td>' + user['fn'] + '</td></tr>\n';


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.