我正在嘗試使用 提取 JSON 物件的值jq --stream,因為真實資料可以是多個千兆位元組的大小。
這是我用于測驗的 JSON,我想在其中提取 的值item:
{
"other": "content here",
"item": {
"A": {
"B": "C"
}
},
"test": "test"
}
jq我正在使用的選項:
jq --stream --null-input 'fromstream(inputs | select(.[0][0] == "item"))[]' example.json
但是,我沒有使用此命令獲得任何輸出。
我發現的一件奇怪的事情是,在上述命令之后洗掉物件時item似乎有效:
{
"other": "content here",
"item": {
"A": {
"B": "C"
}
}
}
結果看起來如預期:
? jq --stream --null-input 'fromstream(inputs | select(.[0][0] == "item"))[]' example.json
{
"A": {
"B": "C"
}
}
但由于我無法控制輸入 JSON,這不是解決方案。
我在 MacOS 上使用 jq 1.6 版。
uj5u.com熱心網友回復:
您沒有截斷流,因此在將其過濾為僅包含以下部分后.item,fromstream缺少最終的回溯項[["item"]]。要么在最后手動添加它(不推薦,這也會在結果中包含頂級物件),或者更簡單地,使用1 | truncate_stream完全剝離第一級:
jq --stream --null-input '
fromstream(1 | truncate_stream(inputs | select(.[0][0] == "item")))
' example.json
{
"A": {
"B": "C"
}
}
或者,您可以使用reduceandsetpath自己構建結果物件:
jq --stream --null-input '
reduce inputs as $in (null;
if $in | .[0][0] == "item" and has(1) then setpath($in[0];$in[1]) else . end
)
' example.json
{
"item": {
"A": {
"B": "C"
}
}
}
要洗掉頂級物件,請.item在末尾過濾,或者與 類似truncate_stream,洗掉路徑的第一項,用于去除[1:]第一級:
jq --stream --null-input '
reduce inputs as $in (null;
if $in | .[0][0] == "item" and has(1) then setpath($in[0][1:];$in[1]) else . end
)
' example.json
{
"A": {
"B": "C"
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/452085.html
