【问题标题】:Debug cgi script on the command line with json使用json在命令行调试cgi脚本
【发布时间】:2018-03-07 20:47:00
【问题描述】:

我有一个 cgi 脚本,它会发送一些简单的 json,我想解析 json,然后返回几个值。我正在尝试在命令行上测试我的 cgi 脚本,但出现此错误:

格式错误的 JSON 字符串,既不是标签、数组、对象、数字、字符串或 原子,在字符偏移量 0 处(在“(字符串结尾)”之前) 1.pl 第 21 行。

这是我的命令行尝试:

$ perl 1.pl '{"a": 1, "b": 2}'
<h1>Software error:</h1>
<pre>malformed JSON string, neither tag, array, object, number, string or atom, at character offset 0 (before &quot;(end of string)&quot;) at 1.pl line 21.
</pre>
<p>
For help, please send mail to this site's webmaster, giving this error message 
and the time and date of the error.

</p>
[timestamp] 1.pl: malformed JSON string, neither tag, array, object, number, string or atom, at character offset 0 (before "(end of string)") at 1.pl 

1.pl:

#!/usr/bin/env perl

use strict;
use warnings;
use 5.020;
use autodie;
use Data::Dumper;
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use JSON;

my $q = CGI->new;

my $json = $q->param('POSTDATA');
my $href = decode_json($json);
my $a = $href->{a};
my $b = $href->{b};

print $q->header,
      $q->start_html("Test Page"),
      $q->h1("Results:"),
      $q->div("a=$a"),
      $q->div("b=$b"),
      $q->end_html;

如果我只返回 $json,这就是我得到的:

$ perl 1.pl '{"a": 1, "b": 2}'
[Wed Mar  7 05:32:19 2018] 1.pl: Use of uninitialized value $json in concatenation (.) or string at 1.pl line 25.
Content-Type: text/html; charset=ISO-8859-1

<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" xml:lang="en-US">
<head>
<title>Test Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>
<h1>Results:</h1><div>--><---</div>
</body>
</html>

所以,我的 cgi 脚本似乎没有从命令行接收任何内容,而 my $href = decode_json($json); 行导致了错误。有没有办法在命令行发送json数据?

【问题讨论】:

    标签: perl cgi


    【解决方案1】:

    好的,我想通了:

    $ perl 1.pl POSTDATA='{"a": 1, "b": 2}'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-27
      • 2011-07-15
      • 1970-01-01
      • 2011-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多