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

$(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;
...

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.

Problem

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

Answers:

Answer

You should use jQuery.getJSON() as mentioned at http://api.jquery.com/jQuery.getJSON/.

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

Answer

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: http://jsfiddle.net/pedrocorreia/s5UrZ/2/

Answer

You can use the JSON parser created by douglas crockford:
https://github.com/douglascrockford/JSON-js

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

var object = JSON.parse(string);

Then you can use it as an array.

Answer

you can use for in statement

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.