我希望这个标题有意义......我对使用Javascript做任何事情都很陌生,而且我一直在寻找一段时间。
我正在使用Node-RED来接收包含JSON的HTTP POST。我在msg.req.body中发布了以下数据,并希望提取targets
内的对象:
{
"policy_url": "https://alerts.newrelic.com/accounts/xxxxx/policies/7477",
"condition_id": 429539,
"condition_name": "Error rate",
"account_id": 773524,
"event_type": "INCIDENT",
"runbook_url": null,
"severity": "CRITICAL",
"incident_id": 50,
"version": "1.0",
"account_name": "Inc",
"timestamp": 1436451988232,
"details": "Error rate > 5% for at least 3 minutes",
"incident_acknowledge_url": "https://alerts.newrelic.com/accounts/xxxxxx/incidents/50/acknowledge",
"owner": "Jared Seaton",
"policy_name": "Default Policy",
"incident_url": "https://alerts.newrelic.com/accounts/xxxxxx/incidents/50",
"current_state": "acknowledged",
"targets": [{
"id": "6002060",
"name": "PHP Application",
"link": "https://rpm.newrelic.com/accounts/xxxxxx/applications/6002060?tw[start]=1436450194&tw[end]=1436451994",
"labels": {
},
"product": "APM",
"type": "Application"
}]
}
我想格式化一个字符串以通过TCP发送,以将事件插入到我们的事件管理系统中。所以我尝试了以下内容:
msg.payload = msg.req.body.targets[0] + "|" + msg.req.body.severity + "|" + msg.req.body.current_state + "|" + msg.req.body.details + "|" + msg.req.body.condition_name + "\n\n";
return(msg);
这会产生以下消息:
[object Object]|CRITICAL|acknowledged|Error rate > 5% for at least 3 minutes|Error rate
我尝试了一些不同的东西,但我得到一个null返回,或者[object Object]。感觉就像我很亲密......
有人可以帮忙吗?
提前致谢。
答案 0 :(得分:0)
target[0]
是一个对象,这就是你看到[object Object]的原因。
您应该msg.req.body.targets[0].name
来访问该对象的属性。
结果消息看起来像这样
PHP Application|CRITICAL|acknowledged|Error rate > 5% for at least 3 minutes|Error rate
答案 1 :(得分:0)
你想要JSON.stringify()
msg.payload = JSON.stringify(msg.req.body.targets[0]) + "|" + msg.req.body.severity + "|" + msg.req.body.current_state + "|" + msg.req.body.details + "|" + msg.req.body.condition_name + "\n\n";
return(msg);
这会将存储在目标数组中第一个插槽中的对象转换为它的字符串表示形式。