我正在尝试使用JQ将JSON转换为其他结构。我可以实现新的结构,但是如果Source中不存在Null对象,我将得到大量的假象,如果它们具有null值,我的客户希望删除这些字段。
当我迭代时,我能够以新格式获取结构。但是还会有其他结构。
代码段-https://stackoverflow.com/a/11776728/4389143
JSON
const app = express();
JQ查询:
{
"amazon": {
"activeitem": 2,
"createdDate": "2019-01-15T17:36:31.588Z",
"lastModifiedDate": "2019-01-15T17:36:31.588Z",
"user": "net",
"userType": "new",
"items": [
{
"id": 1,
"name": "harry potter",
"state": "sold",
"type": {
"branded": false,
"description": "artwork",
"contentLevel": "season"
}
},
{
"id": 2,
"name": "adidas shoes",
"state": null ,
"type": {
"branded": false,
"description": "Spprts",
"contentLevel": "season"
}
},
{
"id": 3,
"name": "watch",
"type": {
"branded": false,
"description": "walking",
"contentLevel": "special"
}
},
{
"id": 4,
"name": "adidas shoes",
"state": "in inventory",
"type": {
"branded": false,
"description": "running",
"contentLevel": "winter"
}
}
],
"product": {
"id": 4,
"name": "adidas shoes",
"source": "dealer",
"destination": "resident"
}
}
}
预期的响应:
.amazon | { userType: .userType, userName: .user, itemCatalog: (.items | map({ itemId: .id, name, state} )) }
通过查询,我得到具有空值或空值的条目的 state:null 。在这些情况下,我想隐藏字段本身。
答案 0 :(得分:0)
尝试此JQ查询:
jq '.amazon| { userType: .userType, userName: .user, itemCatalog: [.items[] | {id: .id, name: .name, state: .state}]}'
警告这并不说明null值。所以这是解决方案的一半。
答案 1 :(得分:-1)
可怕的解决方案,查询后删除它们。必须有更整洁的方法吗? (我今天开始用jq)
.amazon | { userType: .userType, userName: .user, itemCatalog: (.items | map({ itemId: .id, name, state} )) }| del(.itemCatalog[].state |select(. == null))