gpt4 book ai didi

json - 处理 JSON 返回的空值

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:43:10 40 4
gpt4 key购买 nike

我正在运行 ruby​​ 1.9。我有这段代码,它从这两个 /usr/sbin/storcli/c0/bbu show j 中提取 StatusState 的值 & /usr/sbin/storcli/c0/cv show j 命令。

#!/usr/bin/ruby
require 'json'

output_bbu = %x{/usr/sbin/storcli /c0/bbu show j}
output_cv = %x{/usr/sbin/storcli /c0/cv show j}

begin
j = JSON.parse(output_bbu)
k = JSON.parse(output_cv)
result = j["Controllers"][0]["Command Status"]["Status"]

### I'm not sure how to get the value of "State" and store it in "status" variable.

status = k["Controllers"][0]["Response Data"]["Cachevault_Info"][0]["State"]
status = j["Controllers"][0]["Response Data"]["BBU_Info"][0]["State"]

###
rescue Exception => e
puts "CRITICAL: error reading BBU status: #{e}"
exit 2
end

if result != 'Success'
puts "CRITICAL: command not successful, result: #{result}"
exit 2
end

问题:

storcli/c0/cv show jstorcli/c0/bbu show j 两个命令之一在“状态”变量中返回空值,脚本失败并显示错误

undefined method `[]' for nil:NilClass

storcli/c0/cv show j 可以返回“State”的 nil 值,或者 storcli/c0/bbu show j 可以返回 nil。所以我想做的是将“State”的值存储在变量“status”中。

命令输出示例,

$ storcli /c0/cv show j

{
"Controllers":[
{
"Command Status" : {
"Controller" : 0,
"Status" : "Success",
"Description" : "None"
},
"Response Data" : {
"Cachevault_Info" : [
{
"Model" : "CVPM02",
"State" : "Optimal",
"Temp" : "35C",
"Mode" : "-",
"MfgDate" : "2013/09/17"
}
]
}
}
]
}

看,这里它返回了“State”的值作为“Optimal”,所以我想将它的值存储在变量“status”中。

零的示例输出,

$ storcli /c0/bbu show j

{
"Controllers":[
{
"Command Status" : {
"Controller" : 0,
"Status" : "Failure",
"Description" : "None",
"Detailed Status" : [
{
"Ctrl" : 0,
"Status" : "Failed",
"Property" : "-",
"ErrMsg" : "use /cx/cv",
"ErrCd" : 1001
}
]
}
}
]
}

最佳答案

由于您没有从一个命令中获得“响应数据”,您可以使用以下命令

status = k["Controllers"][0]
.fetch(["Response Data"], {})
.fetch(["Cachevault_Info"], {})
.fetch([0], {})["Status"]
status ||= j["Controllers"][0]["Response Data"]["BBU_Info"][0]["State"]

对于 ||=,如果 status = k 的结果是 nil,它将设置 status = j

关于json - 处理 JSON 返回的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40481052/

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