我如何把一个阵列,JSON字符串成JSON对象(红宝石) [英] How do I convert an Array with a JSON string into a JSON object (ruby)

查看:110
本文介绍了我如何把一个阵列,JSON字符串成JSON对象(红宝石)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组,其内容如下:

I have an Array whose content is as follow:

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

请注意:现在该数组的每一项都是一个Hash(不是字符串)。这就是说,如果我这样做把myArray的[0]的.class 我得到的回报。

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]点域

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

例如我想通过调用对象[0]​​。名称或获得开发获得标记 >对象[1] .DESCRIPTION 。

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

这可能吗?我试图利用对我的数组.to_json方法,但它并不完全给我我需要什么。

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.

感谢。

推荐答案

您可以做使用的 结构体 以满足您的需要。

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"

这篇关于我如何把一个阵列,JSON字符串成JSON对象(红宝石)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆