Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy JSON encoding

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?

like image 456
14 revs, 12 users 16% Avatar asked Apr 25 '26 23:04

14 revs, 12 users 16%


1 Answers

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
like image 86
konsolebox Avatar answered Apr 28 '26 12:04

konsolebox