Search code examples
crystal-lang

Crystal convert string to hash from response.body


I am going some HTTP gets and the response body is this structure:

response.body = "{\"temp\": \"val_one\", \"temp2\": \"val_two\"}"

How do I convert this to a Hash, I want to do this:

response.body.to_hash
response.body["temp"] # => val_one

Thanks

edit:

Fixed temp's value. Changed from val_one to \"val_one\"


Solution

  • That seems to be a JSON, so you should use JSON.parse.

    my_hash = JSON.parse response.body
    my_hash["temp"] # => val_one
    

    Pay attention to your data, though - val_one as is is not actually valid JSON. If it is a String, you should quote it (like you did with val_two).

    Example in Crystal Play here.