我是红宝石的新手。我有一个以下格式的现有JSON文件。
{
"ASRtest": {
"ASRHDR": "This is asr HDR",
"ASRTestType": "DevTest",
"Scenario": [
{
"ScenarioNumber": 1,
"ScenarioName": "HTTP Validation",
"ScenarioDescription": "Validate if the API alows access over HTTP",
"ScExecutionStatus": "Execution Complete",
"ScenarioStatus": "In-Complete",
"ScenarioSeverity": false,
"TestCase": [
{
"TestCaseNumber": 1,
"TestCaseName": "HTTP Validation - using POST method ",
"TcExecutionStatus": "Execution Error",
"TcStatus": "NA",
"TcSeverity": "NA"
}
]
}
]
}
}
我正在我的ruby程序中读取此文件,并想要另一个场景到此文件,如
{
"ASRtest": {
"ASRHDR": "This is asr HDR",
"ASRTestType": "DevTest",
"Scenario": [
{
"ScenarioNumber": 1,
"ScenarioName": "HTTP Validation",
"ScenarioDescription": "Validate if the API alows access over HTTP",
"ScExecutionStatus": "Execution Complete",
"ScenarioStatus": "In-Complete",
"ScenarioSeverity": false,
"TestCase": [
{
"TestCaseNumber": 1,
"TestCaseName": "HTTP Validation - using POST method ",
"TcExecutionStatus": "Execution Error",
"TcStatus": "NA",
"TcSeverity": "NA"
}
]
},
{
"ScenarioNumber": 2,
"ScenarioName": "SC2",
"ScenarioDescription": "Desc",
"ScExecutionStatus": "Execution Complete",
"ScenarioStatus": "In-Complete",
"ScenarioSeverity": false,
"TestCase": [
{
"TestCaseNumber": 1,
"TestCaseName": "Some Name ",
"TcExecutionStatus": "Execution Error",
"TcStatus": "NA",
"TcSeverity": "NA"
}
]
}
]
}
}
我已使用以下代码
阅读了该文件@template_file = JSON.parse(File.read('SummaryTemplate.json'))
@ASR_Test = @template_file['ASRtest']
@ASR_Test
@scenario = @ASR_Test['Scenario']
当我尝试以下代码时
@scenario[1]['ScenarioNumber'] = 2
它给我一个错误未定义的方法`[] =' for nil:NilClass(NoMethodError) 变量@scenario只有1次出现,它不允许我添加第二次出现。
有人可以帮我解决这个问题。
答案 0 :(得分:1)
那是因为@scenario = @ASR_Test['Scenario']
,@scenario
会有:
[
{
"ScenarioNumber": 1,
"ScenarioName": "HTTP Validation",
"ScenarioDescription": "Validate if the API alows access over HTTP",
"ScExecutionStatus": "Execution Complete",
"ScenarioStatus": "In-Complete",
"ScenarioSeverity": false,
"TestCase": [
{
"TestCaseNumber": 1,
"TestCaseName": "HTTP Validation - using POST method ",
"TcExecutionStatus": "Execution Error",
"TcStatus": "NA",
"TcSeverity": "NA"
}
]
}
]
并说@scenario[1]
会产生:nil
这意味着,调用@scenario[1]['ScenarioNumber']
会引发异常,说:
`[]=' for nil:NilClass (NoMethodError) the variable @scenario
要解决此问题,您必须在给定索引上添加Hash
对象:
@scenario[1] = {}
然后您的上述代码将起作用:
@scenario[1]['ScenarioNumber'] = 2
答案 1 :(得分:0)
在@scenario
中你有Array
个对象,所以如果你想在这个数组中添加新的哈希,只需使用这样的Array#<<方法。
因为Array是对象,所以可以在此对象中添加数据。
new_scenario = {
"ScenarioNumber" => 2,
"ScenarioName" => "SC2",
"ScenarioDescription" => "Desc",
"ScExecutionStatus" => "Execution Complete",
"ScenarioStatus" => "In-Complete",
"ScenarioSeverity" => false,
"TestCase" => [
{
"TestCaseNumber" => 1,
"TestCaseName" => "Some Name ",
"TcExecutionStatus" => "Execution Error",
"TcStatus" => "NA",
"TcSeverity" => "NA"
}
]
}
@scenario << new_scenario
@template_file
现在包含new_scenario