3

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

Tom Lord
  • 27,404
  • 4
  • 50
  • 77
belgoros
  • 3,590
  • 7
  • 38
  • 76
  • 1
    What are you trying to achieve? If you want to generate a JSON **string** from a ruby hash, then you can `require 'json'`, then use `Hash#to_json` – Tom Lord May 31 '18 at 15:30
  • I'm trying to return some JSON response from a dummy Ping controller (Rails 5, Ruby 2.5.0) as follows: `render json: `. That's why I tried without success to pass in a JSON or an OpenStruct object: `OpenStruct.new(pong: 'OK')`. – belgoros May 31 '18 at 15:35
  • 1
    `render json: {pong: 'ok'}` should work?? – Tom Lord May 31 '18 at 15:37
  • By the way, your console above shows ruby `2.4.0`, not `2.5.0`. – Tom Lord May 31 '18 at 15:37
  • @TomLord, nice catch, I updated `Gemfile`5 sec later to use 2.5.0. Yep, thanks you, your version worked for me. – belgoros May 31 '18 at 15:38
  • If you're updating the ruby version now, then - unless you have a good reason not to - you should use the latest version: `2.5.1`. – Tom Lord May 31 '18 at 15:41

1 Answers1

7

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"
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
  • thank you, the 1st solution worked for me (my bad, I had to pass in a String as you did and not a Hash) – belgoros May 31 '18 at 15:37