无法在Perl中添加到哈希

new*_*per 2 perl hash

我正在读取替换数据的文件,并将输出返回给json。当我尝试将新项目添加到哈希中时,出现以下错误。Not a HASH reference当我使用时,ref()我会HASH作为类型。

我试过了。

my $json_data = decode_json($template);
$json_data->{CommandCenters}{NewItem} = ["haha","moredata"];
Run Code Online (Sandbox Code Playgroud)

给出not a hash reference错误

$json_data如下。

  {
     "Location":"Arkansas",
     "CommandCenters": [
          {
          "secretary": "jill",
          "janitor": "mike"
          }
       ],
  }
Run Code Online (Sandbox Code Playgroud)

添加元素后,我正在寻找以下输出。

{
  "Location":"Arkansas",
  "city": "little rock"
  "CommandCenters": [
   {
      "secretary": "jill",
      "janitor": "mike"
   },
   {
       "NewItem":["whatever","more data"]
   }
   ],
}
Run Code Online (Sandbox Code Playgroud)

如果使用$json_data->{CommandCenters}[0]{NewItem} = ['whatever','sure'];,不会出现错误,但是会得到意外的结果。数据已添加,但位于错误的插槽中。

"commandcenters":
 [
    "secretary":"jill",
    "janitor": "mike",
     "newitem": 
     [
        "whatever","sure"
     ],
 ]
Run Code Online (Sandbox Code Playgroud)

cho*_*oba 9

要将新元素添加到数组,请使用push。在处理数组引用时,我们需要先对其进行取消引用。

push @{ $json_data->{CommandCenters} }, { NewItem => ["haha", "moredata"] };
Run Code Online (Sandbox Code Playgroud)


Dav*_*oss 6

当我尝试将新项目添加到哈希中时,出现以下错误。Not a HASH reference当我使用时,ref()我将HASH作为类型。

注重细节是成功的程序员的一项至关重要的技能。而且您在这里缺少一些细微之处。

当您使用时ref(),我假设您正在将$json_data变量传递给它。这确实是一个哈希引用。但是生成您的行Not a HASH reference是以下行:

$json_data->{CommandCenters}{NewItem} = ["haha","moredata"];
Run Code Online (Sandbox Code Playgroud)

不仅将其$json_data视为哈希引用($json_data->{...}),还将其$json_data->{CommandCenters}视为哈希引用。这就是您的问题所在。$json_data->{CommandCenters}是数组引用,而不是哈希引用。它是通过JSON的一部分生成的,如下所示:

"CommandCenters": [
  {
    "secretary": "jill",
    "janitor": "mike"
  }
]
Run Code Online (Sandbox Code Playgroud)

那些[ .. ]将其标记为数组而不是哈希。您不能将新的键/值对添加到数组。您需要将push()新数据添加到数组的末尾。就像是:

push @{ $json_data->{CommandCenters} }, { NewItem => ["haha", "moredata"] };
Run Code Online (Sandbox Code Playgroud)

这将使您具有以下数据结构:

$VAR1 = {
  'CommandCenters' => [
    {
      'janitor' => 'mike',
      'secretary' => 'jill'
    },
    {
      'NewItem' => [
        'haha',
        'moredata'
      ]
    }
  ],
  'Location' => 'Arkansas'
};
Run Code Online (Sandbox Code Playgroud)

encode_json()将将其转换成你想要的JSON。