我有一个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 "(end of string)") 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数据?
答案 0 :(得分:3)
好的,我明白了:
$ perl 1.pl POSTDATA='{"a": 1, "b": 2}'