ruby - 转换哈希结构

标签 ruby json

<分区>

我有一个大的 JSON 对象(但 x100+):

[
    {
        "category": "category1",
        "text": "some text"
    },
    {
        "category": "category2",
        "text": "some more text"
    },
    {
        "category": "category1",
        "text": "even more text"
    }
]

我如何将其转化为:

{
    "category1": [
        {
            "text": "some text"
        },
        {
            "text": "even more text"
        }
    ],
    "category2": {
        "text": "even more text"
    }
}

如能提供正确方向的任何帮助,我们将不胜感激。

最佳答案

首先,您需要将 JSON 字符串转换为 Ruby 对象。

require "json"
json = %{
[
    {
        "category": "category1",
        "text": "some text"
    },
    {
        "category": "category2",
        "text": "some more text"
    },
    {
        "category": "category1",
        "text": "even more text"
    }
]
}
ary = JSON.parse(json)

现在我们有了一个 Ruby 形式的哈希数组,我们可以操作它了

h = ary.group_by {|i| i["category"]}
#=> {"category1"=>[{"category"=>"category1", "text"=>"some text"}, {"category"=>"category1", "text"=>"even more text"}], "category2"=>[{"category"=>"category2", "text"=>"some more text"}]}

h = h.map {|k,v| {k => v.map {|t| {"text" => t["text"]}}}}
#=> [{"category1"=>[{"text"=>"some text"}, {"text"=>"even more text"}]}, {"category2"=>[{"text"=>"some more text"}]}]

h = h.reduce(&:merge)
#=> {"category1"=>[{"text"=>"some text"}, {"text"=>"even more text"}], "category2"=>[{"text"=>"some more text"}]}

以漂亮的形式打印 JSON 以检查结果

puts JSON.pretty_generate(h)

输出:

{
  "category1": [
    {
      "text": "some text"
    },
    {
      "text": "even more text"
    }
  ],
  "category2": [
    {
      "text": "some more text"
    }
  ]
}

关于ruby - 转换哈希结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34402528/

相关文章:

ruby - 我如何匹配所有 % 除了后跟 s 的百分比?

java - 为什么 Jackson 的 pretty-print 功能不起作用?

android - 应用程序不显示 firebase 通知(广播 Intent 回调 : result=CANCELLED forIntent)

java改变变量参数值

css - 将我编译的 .scss 文件设置为输出到 config.rb 中的根文件夹

.net - 为什么异步 I/O 需要事件循环

arrays - Swift 3 - 如何从包含字符串的索引读取 json 输出

javascript - JQuery从Json文件中读取

ruby - 如何在 Cucumber with Pickle 中使用命名的 Machinist 蓝图

ruby - 如何打印语法高亮的 Ruby 代码?