我有一個JSON obj,在一些操作(如刪除一些作品)後,我打印它,除了我有一些null
值之外,一切看起來都不錯。我如何刪除這些?從JavaScript對象遞歸刪除空值
我用JSON.stringify(obj, null, 2)
方法來打印,這裏是什麼樣子:
{
"store": {
"book": [
null,
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
null,
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
null,
"price": 19.95
}
}
}
我想這是很多緊湊,很乾淨(刪除多餘的3個null
值):
{
"store": {
"book": [
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}
你'bicycle'是無效的語法,因爲'null'的。 –
我想知道'JSON.stringify'的哪個實現產生了無效的JSON。 –
忽略自行車元素,你就在這裏,這是我的錯誤 – lauxp