mreferre
mreferre

Reputation: 6063

How do I convert an Array with a JSON string into a JSON object (ruby)

I have an Array whose content is as follow:

[
     [0] {
                   "name" => “Mark”,
                     "id" => “01”,
            "description" => “User”,
     },
     [1] {
                   "name" => “John”,
                     "id" => “02”,
            "description" => “Developer”,
     }
] 

Note: right now each item of the Array is a Hash (not a string). That is to say that if I do puts myarray[0].class I get hash in return.

I would like to be able to create an object that I can reference as object[i].field.

For example I'd like to be able to get "Mark" by calling object[0].name or get "Developer" by calling object[1].description.

Is this possible? I have tried to leverage the .to_json method against my array but it doesn't quite give me what I need.

Thanks.

Upvotes: 1

Views: 427

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118299

You can do use Struct to meet your need.

array = [
  {
    "name" => "Mark",
    "id" => "01",
    "description" => "User",
  },
  {
    "name" => "John",
    "id" => "02",
    "description" => "Developer",
  }
] 

Customer = Struct.new(:name, :id, :description)
array_of_customers = array.map { |hash| Customer.new(*hash.values) }
array_of_customers[1].name # => "John"
array_of_customers[1].description # => "Developer"

Upvotes: 3

Related Questions