gpt4 book ai didi

arrays - 将新值附加到 ruby​​ 中的现有 JSON 数组

转载 作者:数据小太阳 更新时间:2023-10-29 08:07:05 26 4
gpt4 key购买 nike

我是 ruby 新手。我有以下格式的现有 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

它给我一个错误 undefined method `[]=' for nil:NilClass (NoMethodError)变量@scenario 只出现了 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

关于arrays - 将新值附加到 ruby​​ 中的现有 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41478421/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com