【问题标题】:How do I convert an Array with a JSON string into a JSON object (ruby)如何将带有 JSON 字符串的数组转换为 JSON 对象(ruby)
【发布时间】:2023-03-15 11:25:02
【问题描述】:

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

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

注意:现在 Array 中的每一项都是一个 Hash(不是字符串)。也就是说,如果我执行puts myarray[0].class,我会得到hash 作为回报。

我希望能够创建一个可以引用为object[i].field 的对象。

例如,我希望能够通过调用object[0].name 获得“Mark”或通过调用object[1].description 获得“Developer”。

这可能吗?我试图对我的数组利用 .to_json 方法,但它并不能完全满足我的需求。

谢谢。

【问题讨论】:

    标签: ruby arrays json


    【解决方案1】:

    您可以使用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"
    

    【讨论】:

    • 天哪,这正是我想做的。它完美地工作。非常感谢奥雅纳!
    猜你喜欢
    • 2015-11-21
    • 2021-05-12
    • 1970-01-01
    • 2013-08-29
    • 2018-01-06
    • 2015-01-25
    • 2023-02-15
    • 1970-01-01
    • 2016-03-23
    相关资源
    最近更新 更多