需要帮助从Perl生成JSON

时间:2011-03-01 07:33:26

标签: perl json

我有一些称为节点的结构,每个结构都有一个散列,其中包含有关Node的几个重要特性。我有一个包含一堆节点的图形结构。本质上,我想迭代我的所有节点并创建一些可以将每个节点转换为JSON元素的结构。对于每个节点,我应该在JSON文件中有一个元素及其所有特性(它的名称,代码,它的种群......所有属性)。

我似乎无法弄清楚如何使用JSON:XS ......

my $nodeHash = {}; # the hash I plan to pass to the to_json function
my $metros = {}; #each metro is a Node with a bunch of features
my @array= (); # an array that I populate with nodes

    #some code to populate the array (these are blessed objects)

$nodeHash->{$metros} =  \@array; # metros has a reference to a list of all nodes
my $json = new JSON;   # this syntax is yielding an error for some reason
$json = JSON->allow_blessed([$enable]); #im not sure quite how this works from the documentation
my $json_string = $json->encode_json($nodeHash);
open(JSON, ">output.json") or die "cannot open file for reading: $!";
    print JSON "$json_string";

1 个答案:

答案 0 :(得分:3)

可能最容易的是功能界面。 JSON根据安装的内容选择JSON::XSJSON::PP中的一个。

use JSON;

my $node_hash = {
    a => [ 'text1', 'text2' ],
    b => [ 'what',  'is', 'this' ],
};

print to_json($node_hash);    # {"a":["text1","text2"],"b":["what","is","this"]}