json - 我可以根据输入中的嵌套属性输出带有 jq 的属性吗?
问题描述
这是从使用 jq 从嵌套 JSON 对象中提取选定属性的后续步骤,这使那里的 OP 从嵌套对象中摆脱了大量不需要的属性。
我遇到了同样的问题,但不是一个以 [ 开头的数组,而是一个 JSON 对象流,每个对象都像这样:
{
"localHostName" : "rest-2-17ve6",
"port" : "80",
"requestHeaders" : {
"x-forwarded-port" : "443",
"x-forwarded-host" : "dummy.com",
"content-length" : "15959431",
"accept" : "*/*",
"x-forwarded-for" : "10.1.9.11",
"authorization" : "hash is present",
"expect" : "100-continue",
"forwarded" : "for=10.5.9.1;host=dummy.com;proto=https",
"content-type" : "application/json",
"host" : "dummy.com",
"x-forwarded-proto" : "https",
"user-agent" : "curl/7.51.0"
},
"uri" : "/2/data/saveList",
"protocol" : "HTTP/1.1",
"threadName" : "http-nio-8080-exec-10",
"requestBytes" : 15959431,
"applicationDuration" : 44135,
"responseStatus" : "200",
"remoteIpAddress" : "10.1.10.1",
"responseHeaders" : {
"X-XSS-Protection" : "1; mode=block",
"Content-Type" : "application/json;charset=UTF-8",
"X-Content-Type-Options" : "nosniff",
"Cache-Control" : "no-cache, no-store, max-age=0, must-revalidate",
"Date" : "Wed, 20 Jun 2018 15:53:27 GMT",
"Transfer-Encoding" : "chunked",
"Vary" : "Accept-Encoding",
"X-Frame-Options" : "DENY",
"Expires" : "0",
"Pragma" : "no-cache"
},
"isoDateTime" : "2018-06-20T15:52:42.466913985Z",
"method" : "POST",
"username" : "rd7y1",
"localIpAddress" : "10.129.9.238",
"responseBytes" : 2,
"requestContentExcerpt" : "blah",
"totalDuration" : 44869,
"responseContentExcerpt" : " [] "
}
我想在命令行上过滤流,所以我只得到:
{
"isoDateTime" : "2018-06-20T15:52:42.466913985Z",
"method" : "POST",
"username" : "rd7y1",
"requestHeaders.user-agent" : "Rcurl"
}
我试过cat /logs/json.log | jq -cC 'map(requestHeaders|={user-agent})'
了,但出现语法错误。
解决方案
由于 jq 是面向流的,因此您只需使用
select(...)
而不是map(select(...))
看起来您打算
.requestHeaders."user-agent"
在选择标准中使用。通常建议尽可能避免使用
cat
。根据您声明的要求,您应该删除 -c 命令行选项。
由于“Rcurl”没有出现在您的示例输入中,我将使用确实出现的字符串。
所以在你的情况下,你最终会得到类似的东西:
< /logs/json.log jq '
select(.requestHeaders."user-agent" == "curl/7.51.0")
| {isoDateTime, method, username,
"requestHeaders.user-agent": .requestHeaders."user-agent"}'
推荐阅读
- python - ModuleNotFoundError:没有名为“simple_salesforce”的模块
- fortran - status="old" 的 OPEN 语句创建一个新文件并挂起
- stm32 - 什么可以使奇偶校验位总是高或总是低?
- javascript - MONGODB - 在嵌套查询中查找两个数组的差异
- powershell - 从文本文件创建 CSV 并定义字段
- sql - SQL Server UNION 更改结果中查询的顺序
- javascript - Jasmine 单元测试:this.wvInstance.docViewer.getDocument 不是函数
- python - 最好使用“From x import x”而不是只导入整个库吗?
- vhdl - Quartus RTL 查看器参数与 VHDL 代码不同步。错误 (10344) VHDL
- user-interface - 时间线瓷砖错位