簡體   English   中英

這個JSON.parse reviver函數有什么問題?

[英]What is the problem with this JSON.parse reviver function?

我有以下內容:

 const whitelist = ['prop1', 'prop2', 'result']; const reviver = (key, value) => { if (whitelist.includes(key)) { return value; } else { return undefined; // explicitly delete the entry } }; const theMightyJsonString = '{ "result": { "prop1": "Greetings", "prop2": "Hello", "prop3": "WASSUP!!!!" } }'; console.log(JSON.parse(theMightyJsonString)) console.log(JSON.parse(theMightyJsonString, reviver)) 

現在,我可以將JSON.parse(theMightyJsonString)成功轉換為一個對象,但是如果我像我這樣的JSON.parse(theMightyJsonString, reviver)傳遞我的JSON.parse(theMightyJsonString, reviver)結果是undefined

我錯過了什么?

最后一次調用reviver將使用空字符串作為鍵"" ,這允許您將變換應用於最終對象(在您的情況下,您將其轉換為undefined )。 如果為空字符串添加測試,則它可以正常工作:

 const whitelist = ['prop1', 'prop2', 'result']; const reviver = (key, value) => { if (whitelist.includes(key) || key === '') { return value; } else { return undefined; // explicitly delete the entry } }; const theMightyJsonString = '{ "result": { "prop1": "Greetings", "prop2": "Hello", "prop3": "WASSUP!!!!" } }'; console.log( JSON.parse( theMightyJsonString, reviver ) ); 

JSON.parse()文檔解釋了:

如果指定了reviver ,則在返回之前轉換通過解析計算的值。 具體來說,計算值及其所有屬性(從最嵌套的屬性開始並繼續到原始值本身)分別通過reviver運行。

“繼續原始價值本身”回答了你的問題。
JSON.parse()調用reviver與按鍵'prop1''prop2''prop3'及其相關的值,然后用鍵'result'和它的值(物體)和一個最后的時間與空字符串作為key和整個解析對象作為value

該文檔還提供了您的問題的解決方案:

如果reviver僅轉換某些值而不轉換其他值,則確保按原樣返回所有未轉換的值,否則將從結果對象中刪除它們。

您的代碼應如下所示:

 const whitelist = ['prop1', 'prop2', 'result']; const reviver = (key, value) => { if (key === '' || whitelist.includes(key)) { return value; } else { return undefined; // explicitly delete the entry } }; const theMightyJsonString = '{ "result": { "prop1": "Greetings", "prop2": "Hello", "prop3": "WASSUP!!!!" } }'; console.log(JSON.parse(theMightyJsonString)) console.log(JSON.parse(theMightyJsonString, reviver)) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM