Rumah > Soal Jawab > teks badan
Bolehkah anda memberitahu saya bagaimana untuk mengalih keluar semua objek null dalam json menggunakan javascript?
Saya juga perlu mengalih keluar objek bersarang dengan kekunci null/kosong.
{ "glossary": { "title": "example glossary", "GlossDiv": { "title": "S", "text": null, "GlossList": { "GlossEntry": { "ID": "SGML", "SortAs": "SGML", "GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML", "Abbrev": "ISO 8879:1986", "GlossDef": { "para": "A meta-markup language, used to create markup languages such as DocBook.", "definition": null }, "GlossSee": "markup", "window": { "title": "Sample Konfabulator Widget", "description": "" } } } }, "image": { "src": null, "name": null, "alignment": null }, "text": { "data": "Click Here", "size": null, "style": "bold", "name": "text1", "hOffset": "", "vOffset": "", "alignment": "center", "onMouseUp": null } } }
Keluaran yang diperlukan adalah seperti berikut:
{ "glossary": { "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": { "GlossEntry": { "ID": "SGML", "SortAs": "SGML", "GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML", "Abbrev": "ISO 8879:1986", "GlossDef": { "para": "A meta-markup language, used to create markup languages such as DocBook." }, "GlossSee": "markup", "window": { "title": "Sample Konfabulator Widget" } } } }, "text": { "data": "Click Here", "style": "bold", "name": "text1", "alignment": "center" } } }
Cara memadamkan objek secara rekursif dengan kekunci kosong atau kosong dalam keseluruhan json.
Sama seperti objek image
, kuncinya mempunyai nilai null atau null.
P粉3114649352023-09-09 10:24:59
Anda boleh dapatkannya di JSON.stringify(value, Replacer)
/ JSON.parse 中使用
replacer
/reviver
获得更接近的结果(文本,复活者)
Contoh menggunakan JSON.stringify
let data = {"glossary":{"title":"example glossary","GlossDiv":{"title":"S","text":null,"GlossList":{"GlossEntry":{"ID":"SGML","SortAs":"SGML","GlossTerm":"Standard Generalized Markup Language","Acronym":"SGML","Abbrev":"ISO 8879:1986","GlossDef":{"para":"A meta-markup language, used to create markup languages such as DocBook.","definition":null},"GlossSee":"markup","window":{"title":"Sample Konfabulator Widget","description":""}}}},"image":{"src":null,"name":null,"alignment":null},"text":{"data":"Click Here","size":null,"style":"bold","name":"text1","hOffset":"","vOffset":"","alignment":"center","onMouseUp":null}}} let json = JSON.stringify(data, (key, value) => { return (value === null || value === '') ? undefined : value }, 4) console.log(json)