简体   繁体   中英

Get specific key value pairs with jq

In my sample json below, I can filter records where charge is null with jq -M ' map(select(.charge == null)) '

  [
    {
      "id": 1,
      "name": "vehicleA",
      "state": "available",
      "charge": 100
    },
    {
      "id": 2,
      "name": "vehicleB",
      "state": "available",
    },
    {
      "id": 3,
      "name": "vehicleB",
      "state": "available",
      "charge": 50
    }
  ]

which returns:

{
  "id": 2,
  "name": "vehicleB",
  "state": "available",
}

How would one only get id and the value associated with id of the filtered records so that adding this step to the above query would return 2 ?

Your question is not exactly accurate:

  • The example JSON is invalid, because the last property of the second object has a trailing comma, which should raise a parsing error
  • The output of map(select(.charge == null)) is not an object as in the example, but an array of a single object

In any case, you can extract the .id from the result of map like this:

jq -M 'map(select(.charge == null)) | .[].id' file.json

If you would like an array of ids for items without a charge you could use this filter:

.items | map(select(.charge == null) | .id)

Try it online at jqplay.org

If you want the values enumerated instead of being collected into an array this is better:

.items[] | select(.charge == null) | .id

Try it online at jqplay.org

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