perl - 需要帮助从 Perl 生成 JSON

标签 perl json

我有一些称为节点的结构,每个结构都有一个散列,其中包含有关节点的几个重要功能。我有一个包含一堆节点的图形结构。本质上,我想迭代所有节点并创建某种可以将每个节点转换为 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/

相关文章:

javascript - 如何根据另一个属性获取 JSON 属性

Perl CGI 工具中的 Apache 超时

perl - 缓冲输出文件

perl - 用 Perl 中的 HTML 副本替换特定的内联 CSS

php - 如何在没有js代码的情况下显示json结果数组

ios - json iOS 解析错误

json - jackson :反序列化后如何进行验证?

jquery - 您可以在 jQuery 中向 getJSON 添加 header 吗?

perl - typeglob 别名

perl - 如何同时分配多个 Moose 属性?