Ruby -将数据附加到现有的JSON中



根据这个答案,可以将数据附加到JSON中。

但是当我尝试test.push时,我得到错误NoMethodError: undefined methodpush' '。

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)

如何将以下JSON数据附加到securityRules[]?有时securityRules[]可以是一个空数组,但我仍然想要追加。

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

您可以这样使用Array#push:

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"}}
#   ]
# }