需要帮助从Perl生成JSON
问题描述:
我有一些称为节点的结构,每个结构都有一个关于节点的几个重要特性。我有一个包含一堆节点的图形结构。本质上,我想遍历所有节点并创建某种可以将每个节点转换为JSON元素的结构。对于每个节点,我都应该在JSON文件中包含一个具有所有功能(其名称,代码,群体...所有属性)的元素。需要帮助从Perl生成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";
我不熟悉JSON:XS,但让我发表几条评论。 (1)你是否尝试过'my $ json = new JSON :: XS;'而不是'my $ json = new JSON';(2)你的代码包含语句'$ json = JSON-> allow_blessed([$ enable] );',但是你在哪里设置'$ enable'(如果你没有设置,它是'false')? – MarcoS 2011-03-01 08:16:10
如果您需要将对象传递给json,则可以使用'to_json($ nodeHash,{allow_blessed => 1})''。但它可能不会做你想做的事情,因为它将对象转换为null。对于任意表示,请查看'convert_blessed'选项,并在'Node'中提供'TO_JSON'方法。 – bvr 2011-03-01 09:04:46
通常使用'[]'来表示一个可选参数。这与匿名数组构造函数无关。文档说'allow_blessed'带有一个可选参数,默认为true。但是由于arrayref被认为是一个真正的值,所以传递一个文字'[$ enable]'实际上可以工作以允许有福的对象。 – cjm 2011-03-01 10:21:00