用JQ重塑JSON
Reshape JSON with JQ
我正在尝试使用 JQ 重塑 JSON 文件,但似乎找不到正确的方法。
基本上我是想把一些键变成值,并重新组织JSON的一些部分。
来源 JSON 如下:
{
"ABCC": {
"pairs": {
"CND": {
"tsyms": {
"BTC": {
"useless_variable1": "useless_value1",
"useless_variable2": "useless_value2"
},
"ETH": {
"useless_variable1": "useless_value1",
"useless_variable2": "useless_value2"
}
}
},
"ELF": {
"tsyms": {
"ETH": {
"useless_variable1": "useless_value1",
"useless_variable2": "useless_value2"
},
"BTC": {
"useless_variable1": "useless_value1",
"useless_variable2": "useless_value2"
}
}
}
}
},
"ACX": {
"pairs": {
"PLA": {
"tsyms": {
"AUD": {
"useless_variable1": "useless_value1",
"useless_variable2": "useless_value2"
},
"USDT": {
"useless_variable1": "useless_value1",
"useless_variable2": "useless_value2"
}
}
},
"BTC": {
"tsyms": {
"USDT": {
"useless_variable1": "useless_value1",
"useless_variable2": "useless_value2"
},
"AUD": {
"useless_variable1": "useless_value1",
"useless_variable2": "useless_value2"
}
}
}
}
}
}
预期的 JSON 输出将是这样的:
{
"ABCC": {
"pairs": [
"CND/BTC",
"CND/ETH",
"ELF/ETH",
"ELF/BTC"
]
},
"ACX": {
"pairs": [
"PLA/AUD",
"PLA/USDT",
"BTC/USDT",
"BTC/AUD"
]
}
}
知道我是如何达到这个结果的吗?
谢谢!
直接解决方案的关键是编写一个辅助函数来提取 key/key 字符串:
# emit a stream of key1/key3 strings
def pairs:
keys_unsorted[] as $k1
| .[$k1][]
| keys_unsorted[] as $k3
| "\($k1)/\($k3)";
现在,多亏了 jq 的 |=
运算符,解决方案可以简单地写成:
map_values(.pairs |= [pairs])
我正在尝试使用 JQ 重塑 JSON 文件,但似乎找不到正确的方法。
基本上我是想把一些键变成值,并重新组织JSON的一些部分。
来源 JSON 如下:
{
"ABCC": {
"pairs": {
"CND": {
"tsyms": {
"BTC": {
"useless_variable1": "useless_value1",
"useless_variable2": "useless_value2"
},
"ETH": {
"useless_variable1": "useless_value1",
"useless_variable2": "useless_value2"
}
}
},
"ELF": {
"tsyms": {
"ETH": {
"useless_variable1": "useless_value1",
"useless_variable2": "useless_value2"
},
"BTC": {
"useless_variable1": "useless_value1",
"useless_variable2": "useless_value2"
}
}
}
}
},
"ACX": {
"pairs": {
"PLA": {
"tsyms": {
"AUD": {
"useless_variable1": "useless_value1",
"useless_variable2": "useless_value2"
},
"USDT": {
"useless_variable1": "useless_value1",
"useless_variable2": "useless_value2"
}
}
},
"BTC": {
"tsyms": {
"USDT": {
"useless_variable1": "useless_value1",
"useless_variable2": "useless_value2"
},
"AUD": {
"useless_variable1": "useless_value1",
"useless_variable2": "useless_value2"
}
}
}
}
}
}
预期的 JSON 输出将是这样的:
{
"ABCC": {
"pairs": [
"CND/BTC",
"CND/ETH",
"ELF/ETH",
"ELF/BTC"
]
},
"ACX": {
"pairs": [
"PLA/AUD",
"PLA/USDT",
"BTC/USDT",
"BTC/AUD"
]
}
}
知道我是如何达到这个结果的吗?
谢谢!
直接解决方案的关键是编写一个辅助函数来提取 key/key 字符串:
# emit a stream of key1/key3 strings
def pairs:
keys_unsorted[] as $k1
| .[$k1][]
| keys_unsorted[] as $k3
| "\($k1)/\($k3)";
现在,多亏了 jq 的 |=
运算符,解决方案可以简单地写成:
map_values(.pairs |= [pairs])