Perl6类转换为JSON时排除属性

10

我一直在努力寻找一个可以用于嵌套对象(特别是类)的模块,许多模块都很接近,但我不想将属性设置为 null 以跳过我不需要的值。

如果我能写一个 TO_JSON 方法来返回一个结构,然后由一个模块进行编组就好了。或者,只需在我们不想包含在最终 JSON 文档中的属性上使用 "json-skip"。

类似这样:

class Something {
   has Str $.foo;
   has Str $.bar is json-skip;

}
class Something { 
   has Str $.foo;
   has Str $.bar;

   method TO_JSON {
      return {
          foo => $.foo
      }
   }
}

JSON::Tiny、JSON::Fast、JSON::Marshal等单独构造非常好用,有些甚至可以与嵌套结构一起使用,但目前我找不到排除属性的方法。

最终,我想做到类似于:

my $json-document = to-json(@nestedInstances);

我认为在相关的代码库中提出问题是有意义的。个人认为,采用一个可选的TO-JSON方法(使用.?调用)可能是正确的方式。 - Scimon Proctor
也许你可以使用 {Perl 6} Re: A more elegant way to filter a nested hash? 的变体。 - raiph
2个回答

9
< p > 来自 JSON::Tinyto-json 子程序可以支持多种类型。因此,您可以重新定义该类的行为。

multi sub to-json ( Something $_ ) {
    to-json 'foo' => .foo
}

因此,以下示例可能符合您的要求。
use JSON::Tiny;

class Something { 
   has Str $.foo;
   has Str $.bar;

   method TO_JSON {
      return {
          foo => $.foo
      }
   }
}

multi sub to-json ( $_ where *.can('TO_JSON') ) {
    to-json .TO_JSON
}

my Something $sth .=  new: :foo<interest>, :bar<no_interest>;

say to-json [$sth,2, :$sth];

输出:

[ { "foo" : "interest" }, 2, { "sth" : { "foo" : "interest" } } ]

2

以上答案是被接受的答案,我已经将其作为一个问题提交到JSON::Tiny github存储库中。下面的代码仅是为了澄清对于perl6新手来说正在发生的事情:

use JSON::Tiny;
# The JSON::Tiny module has a bunch of multi to-json subs.
# Here we are creating/adding one that takes an instance that can do "TO_JSON", i.e. has a TO_JSON method
multi to-json ( $_ where *.can('TO_JSON') ) {
   # Execute the method TO_JSON on the passed instance and use one of
   #  the other to-json subs in the JSON::Tiny module that supports the
   #  returned structure
   to-json $_.TO_JSON
}

class Something { 
   has Str $.foo;
   has Str $.bar;

   method TO_JSON {
      return {
          foo => $.foo
      }
   }
}

my Something $sth = Something.new( foo => 'Interested', bar => 'Not interested' );

# The lexically scoped to-json sub above is used because it takes an argument that implements the TO_JSON method
say to-json $sth;

输出:

{ "foo" : "Interested" }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接