Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send a JSON response from a Perl CGI program?

Tags:

I am writing a JSON response from a perl/cgi program. The header's content type needs to be "application/json". But it doesn't seems to be recognized as response is thrown as a text file.

I would be capturing response using JSON library of jQuery. Where am I missing in sending the JSON response.

like image 553
Rakesh Avatar asked Jan 12 '09 13:01

Rakesh


People also ask

How do I read a json file in Perl?

Decoding JSON in Perl (decode_json)Perl decode_json() function is used for decoding JSON in Perl. This function returns the value decoded from json to an appropriate Perl type.

Is Perl used for CGI?

While CGI scripts can be written in many different programming languages, Perl is commonly used because of its power, its flexibility and the availability of preexisting scripts. sent to the server through CGI, the results may be sent to the client.


1 Answers

I am doing this in a perl/cgi program.

I use these in the top of my code:

use CGI qw(:standard);
use JSON;

Then I print the json header:

print header('application/json');

which is a content type of:

Content-Type: application/json

And then I print out the JSON like this:

my $json->{"entries"} = \@entries;
my $json_text = to_json($json);
print $json_text;

My javascript call/handles it like this:

   $.ajax({
        type: 'GET',
        url: 'myscript.pl',
        dataType: 'json',
        data: { action: "request", last_ts: lastTimestamp },
        success: function(data){
            lastTs = data.last_mod;
            for (var entryNumber in data.entries) {
                 //Do stuff here
            }
        },
        error: function(){
            alert("Handle Errors here");
        },
        complete: function() {
        }
    });

You don't necessarily have to use the JSON library if you don't want to install it, you could print straight JSON formatted text, but it makes converting perl objects to JSON prety easy.

like image 194
BrianH Avatar answered Oct 14 '22 20:10

BrianH