![](/img/trans.png)
[英]How do I modify objects within objects using jq while keeping all other objects unchanged?
[英]How do I modify a child object if it exists in array of objects using jq?
我正在尝试使用jq在API请求或响应的各个级别上修改json数据,以支持API版本控制。
这是我的(简化的)测试JSON:
[
{
"note": null,
"patient_id": 1,
"phenotypes": [
{
"name": "Breast carcinoma",
"observation": "present",
"patient_id": 1,
"person_id": 1
},
{
"name": "Breast carcinoma",
"observation": "present",
"patient_id": 1,
"person_id": 1
}
]
},
{
"note": null,
"patient_id": 2
},
{
"note": null,
"patient_id": 3,
"phenotypes": [
{
"name": "Breast carcinoma",
"observation": "present",
"patient_id": 3,
"person_id": 3
},
{
"name": "Breast carcinoma",
"observation": "present",
"patient_id": 3,
"person_id": 3
}
]
}
]
我有一个对象数组。 每个对象都可以具有"phenotypes"
,我需要修改它的内容,并从顶级对象中删除"note"
。
目前我的jq如下:
[ map(del(.note, .age)) | .[] | select(.phenotypes != null) | .phenotypes |= map(del(.person_id)) ]
这几乎可以工作,但是由于select(.phenotypes != null)
,数组中的第二个对象在过滤后再也无法恢复。
我也尝试过使用if-then-else(end),但是我不能使它不是错误,并且我找不到任何可以将其用于进一步表达的示例或文档。
我的预期输出如下:
[
{
"patient_id": 1,
"phenotypes": [
{
"name": "Breast carcinoma",
"observation": "present",
"patient_id": 1
},
{
"name": "Breast carcinoma",
"observation": "present",
"patient_id": 1
}
]
},
{
"patient_id": 2
},
{
"patient_id": 3,
"phenotypes": [
{
"name": "Breast carcinoma",
"observation": "present",
"patient_id": 3
},
{
"name": "Breast carcinoma",
"observation": "present",
"patient_id": 3
}
]
}
]
note
已从根目录中删除。 person_id
已从phenotypes
删除。
这对我有用:
map(del(.note, .age)) |
map(
if .phenotypes then
(.phenotypes |= map(del(.person_id)))
else
.
end
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.