2015-08-21 40 views
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)); 

回答

0

這實際上不是類型比較的問題。

替換函數最初使用空鍵和代表整個JSON對象的值(reference)調用。由於JSON對象不是字符串,因此替換器函數所做的第一件事是用字符串「[object Object]」替換整個JSON對象。

要解決此問題,請檢查密鑰確實存在。因此,您的替代品的功能看起來就像這樣:

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

我有它here工作小提琴爲好。

+0

完美,謝謝@Jake Magill – benishky