在ruby脚本中将hash元素添加到数组

f1tvaqid  于 2023-10-17  发布在  Ruby
关注(0)|答案(2)|浏览(174)

我有ruby代码,可以生成k8s图像的JSON

old_versions_json = "[]"
versions_list = JSON.parse(old_versions_json)
versions_list.push("#{namespace}")
c = versions_list.find { |h| h['name'] == name }
# If the service doesn't exist in the configmap yet, add it
if c.nil?
  puts("[WARNING] service #{name}:#{version} is not present in the configmap.  Adding it.")
  versions_list.push({ "name" => name, "version" => version })
end

这就是JSON结构的由来。

[
  "medusa-dev",
  {
    "name": "pdtk/gravity-device-data-service",
    "version": "3d-dev-1.0.29"
  },
  {
    "name": "pdtk/medusa_dooku",
    "version": "3d-dev-1.1.11"
  }
]

预期输出

{
  "medusa-dev": [
      {
        "name": "pdtk/gravity-device-data-service",
        "version": "3d-dev-1.0.29"
      },
      {
        "name": "pdtk/medusa_dooku",
        "version": "3d-dev-1.1.11"
      }
 ]
}

我做错了什么

rsaldnfx

rsaldnfx1#

这是因为versions_list是一个数组。您希望它是一个键为medusa-dev的Map,Map到一个数组,然后您可以将元素推到该数组上。

old_versions_json = "{}"

versions_list = JSON.parse(old_versions_json)
versions_list[namespace] = []

c = versions_list[namespace].find { |h| h['name'] == name }

# If the service doesn't exist in the configmap yet, add it
if c.nil?
  puts("[WARNING] service #{name}:#{version} is not present in the configmap.  Adding it.")
  versions_list[namespace].push({ "name" => name, "version" => version })
end

顺便说一句,我不知道为什么你提供JSON,然后立即解析它时,你可以只提供一个文字从一开始:

versions_list = { namespace => [] }
vaqhlq81

vaqhlq812#

此要求的正确答案

old_versions_json = "{}"

versions_list = JSON.parse(old_versions_json)
versions_list[namespace] = []

c = versions_list[namespace].find { |h| h['name'] == name }

# If the service doesn't exist in the configmap yet, add it
if c.nil?
  puts("[WARNING] service #{name}:#{version} is not present in the configmap.  Adding it.")
  versions_list[namespace].push({ "name" => name, "version" => version })
end

相关问题