Add hash element to array in ruby script

70 views Asked by At

I have ruby code which generate JSON of k8s images

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

This is how the JSON structure is coming now.

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

expected output

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

what am I doing wrong here?

1

There are 1 answers

6
Dennis Hackethal On

It's because versions_list is an array. You want it to be a map with a key of medusa-dev that maps to an array, which you can then push elements onto.

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

Btw I don't know why you provide JSON and then immediately parse it when you could just provide a literal from the start:

versions_list = { namespace => [] }