【问题标题】:Can I output a property with jq based on a nested property in the input?我可以根据输入中的嵌套属性输出带有 jq 的属性吗?
【发布时间】:2018-06-20 17:34:14
【问题描述】:

这是从Extracting selected properties from a nested JSON object with jq 开始的,它让那里的 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})',但出现语法错误。

【问题讨论】:

    标签: json syntax nested key jq


    【解决方案1】:
    1. 由于 jq 是面向流的,因此您只需使用 select(...) 而不是 map(select(...))

    2. 您似乎打算在选择标准中使用.requestHeaders."user-agent"

    3. 一般建议尽可能避免使用cat

    4. 根据您的要求,您应该删除 -c 命令行选项。

    5. 由于“Rcurl”没有出现在您的示例输入中,我将使用出现的字符串。

    所以在你的情况下,你最终会得到类似的东西:

    < /logs/json.log jq '
      select(.requestHeaders."user-agent" == "curl/7.51.0")
      | {isoDateTime, method, username,
         "requestHeaders.user-agent": .requestHeaders."user-agent"}'
    

    【讨论】:

    • Google for UUOC
    • stackoverflow.com/questions/11710552/… - 我还要指出 UUOC 是 Useless Use of cat 的首字母缩写词,这本身就是一个很好的例子,说明了 use 的无用用法:lol:
    猜你喜欢
    • 2010-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 2017-05-02
    相关资源
    最近更新 更多