Maison > Questions et réponses > le corps du texte
Pouvez-vous me dire comment supprimer tous les objets nuls dans json en utilisant javascript ?
Je dois également supprimer les objets imbriqués avec des clés nulles/vides.
{ "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 } } }
Le résultat requis est le suivant :
{ "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" } } }
Comment supprimer récursivement des objets avec des clés nulles ou vides dans l'ensemble du json.
Tout comme l'objet image
, ses clés ont des valeurs nulles ou nulles.
P粉3114649352023-09-09 10:24:59
Vous pouvez le trouver sur JSON.stringify(value, Replacer)
/ JSON.parse 中使用
replacer
/reviver
获得更接近的结果(文本,复活者)
Exemple utilisant 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)