0

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
  • What is old_versions_json? If it is just empty array, why did you parse it? If it is some really JSON please add it to the question Commented Oct 4, 2023 at 16:47

1 Answer 1

1

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 => [] }
Sign up to request clarification or add additional context in comments.

6 Comments

Looks like versions_list = {} is enough, don't need to parse empty object
Thank you so much I am able to get this output code { "pdtk_dev": [ { "name": "ecr-k8s-secret-creator", "version": "latest" } ] }{ "medusa_dev": [ { "name": "pdtk/medusa_dooku", "version": "3d-dev-1.1.11" } ] }
Still when I checked json structure is not valid for multiple values. Everything should be in a single array but instead ruby is creating separate arrays for each namespace Valid structure { "pdtk_dev": [ { "name": "ecr-k8s-secret-creator", "version": "latest" } ] , "medusa_dev": [ { "name": "pdtk/medusa_dooku", "version": "3d-dev-1.1.11" } ] } could you please suggest on this.
@mechnicov I've already addressed that, read the bottom part of my answer.
Thank you so much @mechnicov my bad I didn't paid attention to it. I am able to generate the required json format in ruby. We can close this question
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.