【问题标题】:Getting the json values where one of the attributes match ruby获取其中一个属性与 ruby​​ 匹配的 json 值
【发布时间】:2021-04-14 14:40:40
【问题描述】:

我有一个 JSON 文件

  { "data": [
      {
          "channel_id":"test1",
          "who_to_ping":"user124",
          "workflow_status":"enabled",
          "non_workflow_status":"disabled",
          "auto_response_status":"enabled"
     },
     {
          "channel_id":"test2",
          "who_to_ping":"user476",
          "workflow_status":"enabled",
          "non_workflow_status":"disabled",
          "auto_response_status":"enabled"
     }
]}

我可以通过这样做访问数据并设置新用户:

channel_id = "test1"
name = "new user"
file_path = "#{Rails.root}/public/slack_config.json"
file = File.read(file_path)
data_hash = JSON.parse(file)
data_hash['data'][0]['who_to_ping'] = name
File.write(file_path, JSON.pretty_generate(JSON.dump(data_hash)))

我需要做的是只更新 channel_id 匹配的数组。例如 channel_id 将是一个传入的变量,它可能是 test1、test2 或其他值。如果我想将 test1 的 who_to_ping 更新为新名称 data_hash['data'][0]['who_to_ping'] 在传递的值是动态的情况下将不起作用。

我可以进行搜索以查看 channel_id 匹配哪个元素,然后如果它的第 8 个元素执行 data_hash['data'][7]['who_to_ping'] 但我确信有更有效的方法。这可能很简单,但我的搜索没有显示任何内容,但我不确定正确的搜索词是什么。

【问题讨论】:

    标签: ruby-on-rails json


    【解决方案1】:

    您可以通过data_hash['data']进行迭代和映射检查数据中的channel_id是否与传递的匹配,如果匹配则更改

    data_hash['data'] = data_hash['data'].map do |data| # you can remove data_hash['data'] = and replace it by a destructible map! 
      if data['channel_id'] == channel_id
        data['who_to_ping'] = name
        # change other fields here too if you want
      end
      data # make sure to return data so the mapping work
    end
    
    File.write(file_path, JSON.pretty_generate(data_hash)) # no need to use dump as pretty_generate already will transform your hash into json
    

    【讨论】:

    • 这很好用,但唯一的问题是当我将它写回文件时,它会弄乱 json 文件的格式,最终看起来像这样:"{\"data\":[{ \"channel_id\":\"my_id\",\"who_to_ping\":\"\"
    • 要存储 JSON,您只需要在您的情况下调用 pretty_generate,漂亮的 generate 将在内部调用 generate,这会将您的哈希转换为 JSON(在您的情况下相当于转储):File.write(file_path, JSON.pretty_generate(data_hash))
    • 啊,你真是个天才,我一直在努力弄清楚为什么会发生这种情况,但这是有道理的并解决了问题。谢谢你让我的一天 Mshka
    猜你喜欢
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 2013-10-05
    • 2021-01-23
    • 1970-01-01
    相关资源
    最近更新 更多