How to filter array of objects by element property values using jq?

后端 未结 4 584
鱼传尺愫
鱼传尺愫 2020-12-01 20:35

I like to filter json files using jq:

jq . some.json

Given the json containing an array of objects:

{
  \"theList\": [
             


        
4条回答
  •  盖世英雄少女心
    2020-12-01 21:12

    Using select(.id == (2, 4)) here is generally inefficient (see below).

    If your jq has IN/1, then it can be used to achieve a more efficient solution:

    .theList[] | select( .id | IN(2,3))
    

    If your jq does not have IN/1, then you can define it as follows:

    def IN(s): first(select(s == .)) // false;
    

    Efficiency

    One way to see the inefficiency is to use debug. The following expression, for example, results in 10 calls to debug, whereas only 9 checks for equality are actually needed:

    .theList[] | select( (.id == (2,3)) | debug )
    
    ["DEBUG:",false]
    ["DEBUG:",false]
    ["DEBUG:",true]
    {
      "id": 2,
      "name": "Fritz"
    }
    ["DEBUG:",false]
    ["DEBUG:",false]
    ["DEBUG:",true]
    {
      "id": 3,
      "name": "Walter"
    }
    ["DEBUG:",false]
    ["DEBUG:",false]
    ["DEBUG:",false]
    ["DEBUG:",false]
    

    index/1

    In principle, using index/1 should be efficient, but as of this writing (October 2017), its implementation, though fast (it is written in C), is inefficient.

提交回复
热议问题