coffeescript非常新,我正在使用ServiceNow的API来获取信息并将其返回聊天。我正在努力解析JSON响应,因为它回来未定义,不确定发生了什么:
snurl = '"https://companyname.service-now.com/api/now/table/incident?sysparm_query=number%3D' + snincmagic + '&sysparm_fields=number%2Csys_id&sysparm_limit=10"'
snpayload = '--request GET -H "Content-Type: application/json" --header "Accept: application/json" ' + " --user 'username':'password'"
tixcurlhack = require "child_process"
tixcurlhack.exec "/usr/bin/curl #{snpayload} #{snurl}", (error, stdout, stderr) ->
if error
msg.send "Error: #{error.code} - #{stderr}"
else
jsonresponsedata = JSON.parse(stdout)
incidentnumber = jsonresponsedata.result.number
incidentsysid = jsonresponsedata.result.sys_id
但即使stdout包含JSON,incidentysid也会以未定义的形式返回:
msg.send "stdout is: " + stdout
msg.send "jsonresponsedata is: " + jsonresponsedata
msg.send "incidentsysid is: " + incidentsysid
> incidentsysid is: undefined.
> jsonresponsedata is: [object Object]
> stdout is: {"result":[{"number":"INC0010689","sys_id":"acb09c8fdb65324063447aecbf96192a"}]}
我是否应该做一些明显的事情,将result.number和result.sys_id放入变量中?
答案 0 :(得分:1)
看起来JSON正在被解析好了,但是您正在错误地访问它:
> stdout is: {"result":[{"number":"INC0010689","sys_id":"acb09c8fdb65324063447aecbf96192a"}]}
将被解析为:
jsonresponsedata = {
result: [
{
number: "INC0010689",
sys_id: "acb09c8fdb65324063447aecbf96192a"
}
]
}
因此,要访问数字和sys_id,您应该使用:
incidentnumber = jsonresponsedata.result[0].number
incidentsysid = jsonresponsedata.result[0].sys_id