我有一个JSON文件,需要从该文件中删除包含数据值为null的节点对象。这能办到吗?
在下面的示例JSON中,我需要删除所有标记都有空值的对象。
{
"store" : {
"book" : [
{
"category" : "reference",
"author" : "Nigel Rees",
"title" : "Sayings of the Century",
"price" : 8.95
},
{
"category" : "fiction",
"author" : "Evelyn Waugh",
"title" : "Sword of Honour",
"price" : 12.99
},
{
"category" : "fiction",
"author" : null,
"title" : "Moby Dick",
"isbn" : "0-553-21311-3",
"price" : 8.99
},
{
"category" : "fiction",
"author" : null,
"title" : "The Lord of the Rings",
"isbn" : "0-395-19395-8",
"price" : 22.99
}
],
"bicycle" : {
"color" : null,
"price" : null
}
},
"expensive" : 10
}
我们试着用震击:
[
// Flatten an array of photo objects into a prefixed
// soup of properties.
{
"operation": "modify-overwrite-beta",
"spec": {
"*": "=recursivelySquashNulls"
}
}
]
但这会导致移除空值,但也不会删除空json字段。
我们正在获得的输出
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {}
},
"expensive": 10
}
预期产出是
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
]
},
"expensive": 10
}
有什么建议我们可以这样做吗?
发布于 2022-10-10 20:58:22
您可以使用以下规范,而不是通过使用"$": "...@(0)"
模式交换键值对来使用recursivelySquashNulls
。
[
{
// convert price values to strings in order to keep the decimal part of them during the interchange operation
"operation": "modify-overwrite-beta",
"spec": {
"store": {
"book": {
"*": {
"price": "=toString"
}
},
"*": {
"price": "=toString"
}
}
}
},
{
// interchange key-value pairs to get rid of the both values null and null object -> { }
"operation": "shift",
"spec": {
"store": {
"book": {
"*": {
"*": {
"$": "&4.&3.&2.@(0)"
}
}
},
"*": {
"*": {
"$": "&3.&2.@(0)"
}
}
},
"*": {
"$": "@(0)"
}
}
},
{
// switch to the original
"operation": "shift",
"spec": {
"store": {
"book": {
"*": {
"*": {
"$": "&4.&3[&2].@(0)"
}
}
},
"*": {
"*": {
"$": "&3.&2.@(0)"
}
}
},
"*": {
"$": "@(0)"
}
}
},
{
// preserve the decimal value as they are
"operation": "modify-overwrite-beta",
"spec": {
"store": {
"book": {
"*": {
"price": "=toDouble"
}
},
"*": {
"price": "=toDouble"
}
}
}
}
]
站点上的演示 http://jolt-demo.appspot.com/是
https://stackoverflow.com/questions/74018893
复制相似问题