'How to remove an element from a json with ruby?

For this json structs:

{
  "a_path": {
    "b_path": [
      {
        "id": 1,
        "name": "a"
      },
      {
        "id": 2,
        "name": "b"
      }
    ]
  }
}

Want to remove id element as:

{
    "a_path": {
      "b_path": [
        {
          "name": "a"
        },
        {
          "name": "b"
        }
      ]
    }
}

Is there a good way? I have tried:

$json_data = JSON.parse(response)["b_path"][0].delete("id")

But got this result:

"a_path": "1"


Solution 1:[1]

Even if .delete would return the mutated hash (which it doesn't, it returns the deleted value), you are assigning $json_data = JSON.parse(response)["b_path"][0].

Just assign the base hash, and mutate it in a loop with .each.

json_data = JSON.parse(response)
json_data['a_path']['b_path'].each { |h| h.delete('id') }
json_data
# => the expected hash

Solution 2:[2]

Try the .delete method. It shoud return you the mutated hash but in actual it returns the deleted value. So only way is you need to assign the base hash and mutate it in a loop and call .delete within that

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rewritten
Solution 2 Hassan Haroon