我有一些称为节点的结构,每个结构都有一个散列,其中包含有关节点的几个重要功能。我有一个包含一堆节点的图形结构。本质上,我想迭代所有节点并创建某种可以将每个节点转换为 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";
最佳答案
可能最简单的是函数式界面。 JSON选择 JSON::XS 之一或JSON::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"]}
关于perl - 需要帮助从 Perl 生成 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5151642/