Search code examples
rubystringhashopenstruct

undefined method 'each_pair' with openstruct


I'm using OpenStruct to manipulate a json like this: OpenStruct.new '{"age":100,"name":"name"}' and I'm getting

NoMethodError: undefined method `each_pair' for "{\"age\":100,\"name\":\"name\"":String

this piece of code was working some time ago, and now it's not.

I'm using Ruby 2.1


Solution

  • Just do as :

    require 'json'
    
    OpenStruct.new(JSON.parse(your_string))
    

    JSON.parse will convert your json string object to Ruby Hash object.