如何使用 jq 将数据从多个输入 json 对象复制到一个输出对象?
How can I copy data from several input json objects to one output object with jq?
我有一个文件,其中每一行都是 json 个对象的数组,例如:
[
{
"ts": "2017-06-13 16:59:35,778"
},
{
"id": 39,
"path": "/1497365920809-31368-6D8E756916AE1",
"messageAttributes": {
"some_obsolete_data": "1497365975532",
"more_obsolete_data": "20",
"c": ""
}
},
{
"id": 40,
"path": "/1497365920809-31368-6D8E756916AE1",
"messageAttributes": {
"some_obsolete_data": "some text",
"data_that_I_Need": "Name,1,Text,1497365975568"
}
}
]
每个数组的第一个对象将始终是我需要的“时间戳”,但以下对象可能感兴趣也可能不感兴趣。
现在我需要让 jq 将每一行转换为包含时间戳和 data_that_I_Need
的 json 对象数组,例如
[
{
"ts": "2017-06-13 16:59:35,778",
"id": 40,
"path": "/1497365920809-31368-6D8E756916AE1",
"messageAttributes": {
"data_that_I_Need": "Name,1,Text,1497365975568"
}
}
]
通过
jq '
.[] |
select(.messageAttributes.data_that_I_Need != null) |
{
id : .id,
path : .path,
messageAttributes: {
dataThat_I_Need: .messageAttributes.data_that_I_Need
}
}
' <my_file.txt
我可以过滤掉过时的数据。
但是如何将第一个对象的“ts”字段添加为输出中的字段?
更新
看来我可以在程序的开头设置一个变量,我可以将其用于以下所有对象...
jq '
.[0].ts as $ts |
.[] |
select(.messageAttributes.data_that_I_Need != null) |
{
ts : $ts,
id : .id,
path : .path,
messageAttributes: {
dataThat_I_Need: .messageAttributes.data_that_I_Need
}
}
' <my_file.txt
更新中的答案非常好,但这里有一个变体说明了几点,特别是不需要变量,{x}
可以用作 [=12= 的缩写]:
.[0]
+ (.[]
| select(.messageAttributes.data_that_I_Need != null)
| {id,
path,
messageAttributes: {dataThat_I_Need: .messageAttributes.data_that_I_Need}} )
我有一个文件,其中每一行都是 json 个对象的数组,例如:
[
{
"ts": "2017-06-13 16:59:35,778"
},
{
"id": 39,
"path": "/1497365920809-31368-6D8E756916AE1",
"messageAttributes": {
"some_obsolete_data": "1497365975532",
"more_obsolete_data": "20",
"c": ""
}
},
{
"id": 40,
"path": "/1497365920809-31368-6D8E756916AE1",
"messageAttributes": {
"some_obsolete_data": "some text",
"data_that_I_Need": "Name,1,Text,1497365975568"
}
}
]
每个数组的第一个对象将始终是我需要的“时间戳”,但以下对象可能感兴趣也可能不感兴趣。
现在我需要让 jq 将每一行转换为包含时间戳和 data_that_I_Need
的 json 对象数组,例如
[
{
"ts": "2017-06-13 16:59:35,778",
"id": 40,
"path": "/1497365920809-31368-6D8E756916AE1",
"messageAttributes": {
"data_that_I_Need": "Name,1,Text,1497365975568"
}
}
]
通过
jq '
.[] |
select(.messageAttributes.data_that_I_Need != null) |
{
id : .id,
path : .path,
messageAttributes: {
dataThat_I_Need: .messageAttributes.data_that_I_Need
}
}
' <my_file.txt
我可以过滤掉过时的数据。
但是如何将第一个对象的“ts”字段添加为输出中的字段?
更新
看来我可以在程序的开头设置一个变量,我可以将其用于以下所有对象...
jq '
.[0].ts as $ts |
.[] |
select(.messageAttributes.data_that_I_Need != null) |
{
ts : $ts,
id : .id,
path : .path,
messageAttributes: {
dataThat_I_Need: .messageAttributes.data_that_I_Need
}
}
' <my_file.txt
更新中的答案非常好,但这里有一个变体说明了几点,特别是不需要变量,{x}
可以用作 [=12= 的缩写]:
.[0]
+ (.[]
| select(.messageAttributes.data_that_I_Need != null)
| {id,
path,
messageAttributes: {dataThat_I_Need: .messageAttributes.data_that_I_Need}} )