Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get specific key value pairs with jq

Tags:

json

bash

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?

like image 618
the_darkside Avatar asked Nov 21 '17 20:11

the_darkside


People also ask

How do you find the key value pair in jq?

Objective: Parse the json from a file or end-point using `jq` and retrieve id-value pair for further process. Additional condition: if the field `name` have pattern: “test1, test2, test3… testN” then create a CSV file with fields: id,name,value.

How do you find key value pairs?

In order to get a key-value pair from a KiiObject, call the get() method of the KiiObject class. Specify the key for the value to get as the argument of the get() method. The value of the key at the first level of the JSON document hierarchy will be obtained.

What types of values can you have in JSON key value pairs?

JSON is basically a collection of name/value pairs, where the name will always be a string and values can be a string (in double quotes), a number, a boolean (true or false), null, an object, or an array. Each name-value pair will be separated by a comma.

What is the output of jq?

jq usually outputs non-ASCII Unicode codepoints as UTF-8, even if the input specified them as escape sequences (like "\u03bc"). Using this option, you can force jq to produce pure ASCII output with every non-ASCII character replaced with the equivalent escape sequence.


2 Answers

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

like image 131
jq170727 Avatar answered Oct 11 '22 16:10

jq170727


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
like image 23
janos Avatar answered Oct 11 '22 17:10

janos