简体   繁体   中英

How do I filter keys from JSON using JQ?

I've got a huge JSON object and I want to filter it down, to a small % of the available fields. I've searched some similar questions, such as enter link description here but that is for an array of objects. I have a JSON object that looks something like:

{
"timestamp":1455408955250999808,
"client":  
    {
    "ip":"76.72.172.208",
    "srcPort":0,
    "country":"us",
    "deviceType":"desktop"},
"clientRequest":
    {
    "bytes":410,
    "bodyBytes":0}
  }

What I'm trying to do is create a new JSON object that looks likes:

{
"timestamp":1455408955250999808,
"client":  
    {
    "ip":"76.72.172.208",
     }
"clientRequest":
    {
    "bytes":410
    }
}

So effectively filter down the data. I've tried: | jq 'map({client.ip: .client.ip, timestamp: .timestamp})' | jq 'map({client.ip: .client.ip, timestamp: .timestamp})' and I continue to get:

jq: error (at <stdin>:0): Cannot index number with string "client"

Even the most simple | jq 'map({timestamp: .timestamp})' | jq 'map({timestamp: .timestamp})' is showing the same error.

I thought I could access the K,V pairs and use the map function as the person did for his array in the question linked above. Any help much appreciated.

Huzzah. Simple enough really :)

cat LogSample.txt | jq  '. | {Id: .Id, client: {ip: .client.ip}}'

Basically define the object yourself :)

It looks like it will be simplest if you construct the object you want. Based on your example, you could do so using the following filter:

{ timestamp,
  client: { ip: .client.ip },
  clientRequest: {bytes: .clientRequest.bytes }
}

By contrast, map expects its input to be an array, whereas your input is a JSON object.

Please also note that jq provides direct ways to remove keys as well, eg using del/1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM