使用jq将Json文件中表格形式的元素相关联 [英] Relate elements in table form from Json file with jq
问题描述
我是jq
的新手,我有以下代码来获取每个名为Abc
的元素的列表值:
I'm new to jq
and I have the following code to obtain tabulated the values for each element called Abc
:
["Abc"], ( .. | objects | select(has("Abc")) | [.["Abc"]] ) | @tsv
这是我得到的当前输出:
This is the current output I get:
"Abc"
"4"
"2"
"1"
"9"
"3"
"2"
"4"
"9"
我想在左侧添加4列,以为每个Abc
值显示相应的页面,行和列.另外,如果有可能,请在第一列中添加一个从1到"Abc"元素个数的计数器.
I would like to add 4 columns to the left to show for each Abc
value the corresponding page, row and column. Additionally if possible as first column add a counter from 1 to number of "Abc" elements.
在下面,我将显示当前输出,并与所需的输出和Json文件的结构进行比较,以阐明:
Below I show the current output, compared with the desired output and the structure of the Json file in order to clarify:
输入的Json文件如下:
The input Json file is below:
{
"document": {
"page": [
{
"@index": "0",
"image": {
"Abc": "4"
}
},
{
"@index": "1",
"row": [
{
"column": [
{
"text": {
"Abc": "2"
}
}
]
},
{
"column": [
{
"text": {
"Abc": "1"
}
},
{
"text": {
"Abc": "9"
}
}
]
},
{
"column": [
{
"text": {
"Abc": "3"
}
}
]
}
]
},
{
"@index": "2",
"row": [
{
"column": [
{
"text": {
"Abc": "2"
}
}
]
},
{
"column": [
{
"text": {
"Abc": "4"
}
},
{
"text": {
"Abc": "9"
}
}
]
}
]
}
]
}
}
我希望有人能帮助我.预先感谢.
I hope someone could help me. Thanks in advance.
推荐答案
以下解决方案使用paths
并具有多个优点,包括简洁,简单,并且可以轻松地适应不同位置的数据.格式.
The following solution uses paths
and has several advantages, including brevity, simplicity, and that it can easily be adapted to a handle data that is in a different format.
为清楚起见,我们首先定义一个添加行号的函数:
For clarity, we begin by defining a function that adds the row numbers:
# add a sequential id, starting at 1
def tsvRows(s):
foreach s as $s (0; .+1; [.] + $s)
| @tsv;
(["counter", "page", "row", "column", "Abc"] | @tsv),
tsvRows(paths as $p
| select($p[-1] == "Abc")
| getpath($p) as $v
| $p
| .[2] as $page
| (if .[3] == "row" then .[4] else null end) as $row
| (if .[5] == "column" then .[6] else null end) as $column
| [$page, $row, $column, $v] )
这篇关于使用jq将Json文件中表格形式的元素相关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!