如何在Perl中创建特定的json对象

时间:2019-05-03 04:22:00

标签: json perl sigma.js

我正在编写一个脚本,该脚本允许使用特定图形的信息创建一个json对象,以便与SigmaJS一起使用。

需要强调的是,用户必须指出必须进行多少次迭代才能定义图中将存在的节点数。 我是这种语言的新手,例如,将代码中的迭代放在5中。

use strict;
use warnings;
use JSON;
my $json_obj = new JSON;
my %perl_data;


for (my $i=0; $i <= 5 ; $i++) {
    $perl_data{nodes} = [{id => "..", label => "..", label => "..", x => ".." , y => ".." , size => ".."}];
    $perl_data{edges} = [{id => "..", source => "..", target => "..", color => ".."}];
}


print $json_obj->pretty->encode(\%perl_data);

我得到这个结果:

{
   "nodes" : [
      {
         "x" : "..",
         "id" : "..",
         "y" : "..",
         "label" : "..",
         "size" : ".."
      }
   ],
   "edges" : [
      {
         "target" : "..",
         "id" : "..",
         "color" : "..",
         "source" : ".."
      }
   ]
}

但是我需要这样的东西:

{
  "nodes": [
    {
      "id": "n0",
      "label": "A node",
      "x": 0,
      "y": 0,
      "size": 3
    },
    {
      "id": "n1",
      "label": "Another node",
      "x": 3,
      "y": 1,
      "size": 2
    },
    {
      "id": "n2",
      "label": "And a last one",
      "x": 1,
      "y": 3,
      "size": 1
    }
  ],
  "edges": [
    {
      "id": "e0",
      "source": "n0",
      "target": "n1"
    },
    {
      "id": "e1",
      "source": "n1",
      "target": "n2"
    },
    {
      "id": "e2",
      "source": "n2",
      "target": "n0"
    }
  ]
}

1 个答案:

答案 0 :(得分:2)

您要反复设置$perl_data{nodes}$perl_data{edges},而不是添加到它们引用的数组中。

my %perl_data = (
   nodes => [],
   edges => [],
);

for my $i (0..5) {
   push @{ $perl_data{nodes} }, {
      id    => "..",
      label => "..",
      x     => "..",
      y     => "..",
      size  => "..",
   };

   push @{ $perl_data{edges} }, {
      id     => "..",
      source => "..",
      target => "..",
      color  => "..",
   };
}