简体   繁体   中英

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM