JSON.parse({"pong": "ok"}) TypeError: no implicit conv" /> JSON.parse({"pong": "ok"}) TypeError: no implicit conv" /> JSON.parse({"pong": "ok"}) TypeError: no implicit conv"/>

Use JSON.parse to parse OpenStruct or a hash

2.6k Views Asked by At

I tried to parse a simple JSON like that:

JSON.parse({"pong": "ok"})

and it failed

2.4.0 :014 > JSON.parse({"pong": "ok"})
TypeError: no implicit conversion of Hash into String
    from (irb):14

What's wrong here ? Why should I convert to String ?

Another try, with OpenStruct this time:

2.4.0 :001 > pong = OpenStruct.new(pong: 'OK')
 => #<OpenStruct pong="OK"> 
2.4.0 :002 > JSON.parse(pong)
TypeError: no implicit conversion of OpenStruct into String
    from (irb):2

The same ? Thank you

1

There are 1 best solutions below

1
Aleksei Matiushkin On

JSON.parse parses json and json means String:

JSON.parse('{"pong": "ok"}')
#⇒ {"pong"=>"ok"}

Also, you might parse json string into OpenStruct:

JSON.parse('{"pong":"ok"}', object_class: OpenStruct).pong
#⇒ "ok"