0
我试图将JSON对象内的任何项目转换为字符串。 JSON.stringify不起作用,因为它不会转换单个值。如果它是一个对象或数字,我希望整个对象是一个字符串。如何测试typeof是不是一个字符串。我不明白为什么这不起作用...typeof比较不等于失败(JAVASCRIPT)
if (typeof(value) !== 'string') {
return String(value);
}
任何见解?下面是一个完整的例子:
var myjson = {
"current_state":"OPEN",
"details":"Apdex < .80 for at least 10 min",
"severity":"WARN",
"incident_api_url":"https://alerts.newrelic.com/api/explore/applications/incidents/1234",
"incident_url":"https://alerts.newrelic.com/accounts/99999999999/incidents/1234",
"owner":"user name",
"policy_url":"https://alerts.newrelic.com/accounts/99999999999/policies/456",
"runbook_url":"https://localhost/runbook",
"policy_name":"APM Apdex policy",
"condition_id":987654,
"condition_name":"My APM Apdex condition name",
"event_type":"INCIDENT",
"incident_id":1234
};
function replacer(key, value) {
if (typeof(value) !== 'string') {
return String(value);
}
return value;
}
console.log(JSON.stringify(myjson, replacer));
完美,谢谢@Jake Magill – benishky