Consider the following:
z = [{"x" => 5}, 2, 3].lazy.map{ |i| i}
#=> #<Enumerator::Lazy: #<Enumerator::Lazy: [{"x"=>5}, 2, 3]>:map>
z.first
#=> {"x"=>5}
When I try to convert z into JSON, I get the following unexpected result:
z.to_json
#=> "\"#<Enumerator::Lazy:0x00000001cb0448>\""
Why isn't to_json enumerating this lazy enumerator?
to_json does not process enumerators. It only dumps its string notation:
> [].to_enum.to_json
=> "\"#<Enumerator:0x00000002503190>\""
You need to convert your enumerator to an array first:
> z.to_a.to_json
=> "[{\"x\":5},2,3]"
To clarify further, the array has its own generator module:
> [].method(:to_json).owner
=> JSON::Ext::Generator::GeneratorMethods::Array
Whereas the enumerator only has the default:
> [].to_enum.method(:to_json).owner
=> JSON::Ext::Generator::GeneratorMethods::Object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With