需要从Perl生成JSON的帮助吗

需要从Perl生成JSON的帮助吗,perl,json,Perl,Json,我有几个称为节点的结构,每个结构都有一个哈希,其中包含关于节点的几个重要特性。我有一个包含一堆节点的图结构。从本质上讲,我希望迭代所有节点,并创建某种结构,将每个节点转换为JSON元素。也就是说,对于每个节点,我应该在JSON文件中有一个元素及其所有特性(名称、代码、填充量……所有属性) 我似乎不知道如何使用JSON:XS my $nodeHash = {}; # the hash I plan to pass to the to_json function my $metros = {}; #

我有几个称为节点的结构,每个结构都有一个哈希,其中包含关于节点的几个重要特性。我有一个包含一堆节点的图结构。从本质上讲,我希望迭代所有节点,并创建某种结构,将每个节点转换为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";

最简单的可能是功能接口。选择其中一个或基于安装的内容

use JSON;

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

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

我不熟悉JSON:XS,但让我做几点评论。(1) 您是否尝试过
my$json=newjson::XS
而不是
my$json=newjson(2)您的代码包含语句
$json=json->allow_bized([$enable])
,但是您在哪里设置
$enable
(如果您没有设置,则设置为
false
)?如果您需要将对象传递到json中,您可以使用
来传递json($nodeHash,{allow\u founded=>1})
。但它可能不会做您想要的事情,因为它会将对象转换为
null
。对于任意表示,请查看
convert\u
选项,并在
节点中提供
TO\u JSON
方法。通常使用
[]
指示可选参数。这与匿名数组构造函数无关。文档中说,
allow\u
接受一个可选参数,默认为true。但是由于arrayref被认为是一个真值,因此传递一个文本
[$enable]
实际上可以允许受祝福的对象。@cjm关于
[$enable]
,你说得对:我没有仔细阅读文档!