简体   繁体   English

如何将带有JSON字符串的数组转换为JSON对象(ruby)

[英]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). 注意:现在,Array的每个项都是一个哈希(不是字符串)。 That is to say that if I do puts myarray[0].class I get hash in return. 也就是说,如果我确实puts myarray[0].class我会得到hash作为回报。

I would like to be able to create an object that I can reference as object[i].field . 我希望能够创建一个我可以作为object[i].field引用的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 . 例如,我希望能够通过调用object[0].name来获取“Mark”,或者通过调用object[1].description获取“Developer”。

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. 我曾尝试对我的数组使用.to_json方法,但它并不能完全满足我的需求。

Thanks. 谢谢。

You can do use Struct to meet your need. 您可以使用Struct来满足您的需求。

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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