typeof 比较不等于失败 (JAVASCRIPT)

typeof comparison NOT equal to fails (JAVASCRIPT)

我正在尝试将 JSON 对象中的任何项目转换为字符串。 JSON.stringify 不起作用,因为它不转换单个值。如果它是一个对象或数字,我希望整个对象是一个字符串。如何测试 typeof 是否不是字符串。我不明白为什么这不起作用...

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));

这实际上不是 typeof 比较的问题。

replacer 函数最初是用一个空键和一个代表整个 JSON 对象 (reference) 的值调用的。由于 JSON 对象不是字符串,替换函数做的第一件事就是用字符串“[object Object]”替换整个 JSON 对象。

要解决此问题,请检查密钥是否确实存在。因此,您的替换函数将如下所示:

function replacer(key, value) {
    if (key && (typeof(value) !== 'string')) {
        return String(value);
    }
    return value;
}

我也有一个 fiddle here