【问题标题】:Perl XML::Twig send final output to JSONPerl XML::Twig 将最终输出发送到 JSON
【发布时间】:2018-02-17 11:26:19
【问题描述】:

我有以下代码可以擦除肥皂信封和正文以及保持根的 XML 字符串,我想获取最终输出并发送到 JSON。 -谢谢

use XML::Twig;
use JSON;

$xml = '<soap:Envelope><Servers>10.20.200.11</Servers></soap:Envelope>';

my $twig = XML::Twig->new( twig_roots => { Servers => 1 },
    twig_handlers => { 
        'soap:Envelope' => sub { $_->erase() },
    },
    pretty_print  => 'indented',
 );

 $twig->parse($xml); 

 my $output = $twig->print;

 $json = JSON->new->allow_nonref;

 $pretty_printed = $json->pretty->encode($output); # <-- This dosen't work!!

 # finally print json
 print $pretty_printed;



So if the XML looks like this - I added a node
$xml = '<Envelope><Servers><Server>10.20.200.11</Server></Servers></Envelope>';

I would expect the JSON to look like this 

 {
   "Servers" : {
        "Server" : "10.20.200.11"
    }
 }

【问题讨论】:

  • 请始终在您的 Perl 代码中使用 use strictuse warnings。尤其是在这里寻求帮助时。
  • $twig-&gt;print 打印树枝或树的字符串化 XML 版本,并返回 $twig 对象本身。所以你将$twig 分配给$output。然后将该对象传递给 JSON,它无法转换它,因为它不知道如何处理一个有福的数据结构(即一个对象)。 XML 比 JSON 复杂得多,它有一个额外的维度。对于您的示例,已经有几种方法可以在 JSON 中对其进行编码。你希望它如何映射?

标签: json xml perl


【解决方案1】:

XML::Twig 具有与XML::Simple 类似的a simplify method(不应使用!)。您可以使用它,但它对您的示例不是很有帮助。

my $json = JSON->new->allow_nonref;
my $pretty_printed = $json->pretty->encode( $twig->simplify );

这将输出

"10.20.200.11"

这是有效的 JSON,但缺少 Servers。我希望像

{ "Servers" => "10.20.200.11" }

XML::Simple the KeepRoot option 会这样做,而 XML::Twig 的文档声称应该查看 XML::Simple 的文档以获取 simplify 的选项。

返回一个类似于 XML::Simple 的可疑数据结构。选项与 XMLin 选项相同,请参阅 XML::Simple 文档了解更多详细信息(或使用 DATA::dumper 或 YAML 转储数据结构)

但是,它does not allow 那个选项。


更好的计划可能是编写您自己的代码,以便根据您想要的格式进行转换。

【讨论】:

    【解决方案2】:
     my $output = $twig->print;
    

    我想你想要

     my $output = $twig->sprint;
    

    在那里,所以你得到了字符串而不是树枝对象(感谢 simbabque)

    这只会将变量输出为 JSON 字符串,而不是从 XML 生成数据结构

    【讨论】:

    • 这就像一个魅力 $json->pretty->encode($twig->sprint);谢谢!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多