使用perl JSON模块进行解码时,无法将字符串用作HASH引用错误

时间:2010-12-30 19:51:17

标签: perl json

当我这样做时:

use strict;
use JSON;
$json_ref = $json->decode($json_data);

我的$ json_ref结构是使用字符串作为哈希引用创建的。我通过Data :: Dumper查看,即:

print STDERR "JSON: " . Dumper($json_ref);

有没有办法解码JSON所以它不使用字符串作为哈希引用?或者我只是在perl中使用JSON数据时不启用stric?

2 个答案:

答案 0 :(得分:1)

似乎对我有用,请你发布你的JSON示例和你得到的内容吗?

use strict;
# JSON example text from http://www.json.org/example.html
my $js = qq[

{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
        "title": "S",
        "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                    "para": "A meta-markup language, used to create markup languages such as DocBook.",
                    "GlossSeeAlso": ["GML", "XML"]
                    },
                 "GlossSee": "markup"
                }
            }
        }
    }
}

];

use JSON;
use Data::Dumper;
my $json = new JSON();
my $json_ref = $json->decode($js);
print Data::Dumper->Dump([$json_ref]);

输出:

$VAR1 = {
  'glossary' => {
          'GlossDiv' => {
          'GlossList' => {
                   'GlossEntry' => {
                     'GlossDef' => {
                     'para' => 'A meta-markup language, used to create markup languages such as DocBook.',
                     'GlossSeeAlso' => [
                         'GML',
                         'XML'
                       ]
                   },
                     'GlossTerm' => 'Standard Generalized Markup Language',
                     'ID' => 'SGML',
                     'SortAs' => 'SGML',
                     'Acronym' => 'SGML',
                     'Abbrev' => 'ISO 8879:1986',
                     'GlossSee' => 'markup'
                   }
                 },
          'title' => 'S'
        },
          'title' => 'example glossary'
        }
        };

答案 1 :(得分:0)

当我没有设置'application / json'的正确内容类型时,我在向Catalyst :: Controller :: REST执行JSON POST时遇到了这个问题