【发布时间】:2020-08-22 14:34:16
【问题描述】:
我有一个相对较大的 JSON 文件,其中包含大量我不需要的数据。
我想只保留我感兴趣的元素,但我想保留一般结构。
[
{
"name" : "foo",
"age" : 12,
"weight": 23,
"colors": {
"head":{
"hair": "blue",
"eyes": "green"
}
}
},
{
"name" : "bar",
"age" : 42,
"weight": 54,
"colors": {
"head":{
"hair": "blue",
"eyes": "blue"
}
}
},
{
"name" : "baz",
"age" : 65,
"weight": 439,
"colors": {
"head":{
"hair": "green",
"eyes": "red"
}
}
}
]
输出应如下所示:
{
"name": "foo",
"colors": {
"head": {
"eyes": "green"
}
}
}
{
"name": "bar",
"colors": {
"head": {
"eyes": "blue"
}
}
}
{
"name": "baz",
"colors": {
"head": {
"eyes": "red"
}
}
}
我的实际输入对象每个顶级对象有大约 100 个叶键,我需要大约 10 个叶键,而且几乎所有叶键都位于层次结构的不同级别。
我研究了一些 json 处理 API(例如 javascript、lodash 和 jq),但找不到这样的机制。它们主要依赖于以简单语法创建新对象,需要从头开始构造对象。
喜欢:
jq '[.[]| {name: .name, colors:{head:{eyes: .colors.head.eyes}}}]'
层次结构很深,这有点混乱。
我是否错过了一些可以更轻松地指定深层对象键的东西,例如:
.[] | {name: .name, colors.head.eyes = .colors.head.eyes}
或者更方便一些:一些子键过滤机制,比如
.[] | filteKeys(["name", "colors.head.eyes"])
我更喜欢一些支持命令行的程序,所以我尝试使用 JQ。
【问题讨论】: