Home > Mobile >  Ruby - Append data to existing JSON
Ruby - Append data to existing JSON

Time:07-13

According to this answer, its possible to append data to JSON.

But when I try test.push I get the error NoMethodError: undefined method push' `.

NETWORK_SG = Azure::Armrest::Network::NetworkSecurityGroupService.new(conf)
network_sg = NETWORK_SG.get('testing_123', rg)
test = network_sg.properties

puts test

{
  "provisioningState": "Succeeded",
  "resourceGuid": "test",
  "securityRules": [
    {
      "name": "SSH",
      "id": "SSH",
      "etag": "18",
      "type": "Microsoft/securityRules",
      "properties": {}
    }
  ]
}

options = {"key": "value"}
test.push(options)

How can I append the following JSON data to securityRules[]? Sometimes securityRules[] can be a empty array but I still want to append.

{
    :name => 'rule_2',
    :properties => {
      :protocol          => 'TCP',
      :sourceAddressPrefix => '*',
      :destinationAddressPrefix => '*',
      :access => 'Allow',
      :destinationPortRange => '22',
      :sourcePortRange => '*',
      :priority => '301',
      :direction => 'Inbound',
    }
  }

CodePudding user response:

You can use Array#push like this:

test = {
  :provisioningState=>"Succeeded",
  :resourceGuid=>"test",    
  :securityRules=>[
    {:name=>"SSH", :id=>"SSH", :etag=>"18",:type=>"Microsoft/securityRules", :properties=>{}}
  ]
}
new_rule = {
  :name => 'rule_2',
  :properties => {
    :protocol          => 'TCP',
    :sourceAddressPrefix => '*',
    :destinationAddressPrefix => '*',
    :access => 'Allow',
    :destinationPortRange => '22',
    :sourcePortRange => '*',
    :priority => '301',
    :direction => 'Inbound',
  }
}

test[:securityRules].push(new_rule)
test
# {
#   :provisioningState=>"Succeeded",
#   :resourceGuid=>"test",
#   :securityRules=> [
#     {:name=>"SSH", :id=>"SSH", :etag=>"18", :type=>"Microsoft/securityRules", :properties=>{}},
#     {:name=>"rule_2",:properties=>{:protocol=>"TCP",:sourceAddressPrefix=>"*",:destinationAddressPrefix=>"*",:access=>"Allow",:destinationPortRange=>"22",:sourcePortRange=>"*",:priori# ty=>"301",:direction=>"Inbound"}}
#   ]
# }

CodePudding user response:

You can use Ruby merge method to append new hash into existing.

here is link: https://apidock.com/ruby/Hash/merge[![enter image description here]1]1

  • Related