The Crystal Programming Language Forum

To_json without arguments

I’m trying to print out some JSON and the following works in the playground without error:

require  "yaml"
value = %[{"hello": "world"}]
parsed = YAML.parse(value).to_json

Returning "{\"hello\":\"world\"}"String

But trying to run the same results in the predicable error:

Error: wrong number of arguments for ‘YAML::Any#to_json’ (given 0, expected 1)

What’s happening here? Is the playground doing some magic? Is there a shorter way to get this into a string without doing:

io =
builder = io
text = parsed.to_json builder

Can you share the code that’s actually not working, ideally with a playground link that reproduces it?

EDIT: Oh sorry, I took and the following works in the playground without error: to mean it actually works, but it doesn’t: Carcin

The problem is you need to require "json" given that’s what allows for converting YAML::Any into JSON.

It works in the playground because every program there is prepended with this:

That includes the agent, which is defined here:

That does require "json".

Eventually the playground could start using the interpreter so this won’t be a problem anymore.

1 Like

Aha, it all makes sense now. Thanks guys!

For anyone else you can look here to see the implementation. There’s even a #to_pretty_json which makes me extra :grinning: