Skip to content

Instantly share code, notes, and snippets.

@xonixx xonixx/jq-vs-jsqry.md

Last active Jul 1, 2020
Embed
What would you like to do?
jq vs jsqry

As per https://codefaster.substack.com/p/mastering-jq-part-1-59c

Pretty print json

$ echo '{"k1": [{"k2": [9]}]}' | jq '.'
{
  "k1": [
    {
      "k2": [
        9
      ]
    }
  ]
}

$ echo '{"k1": [{"k2": [9]}]}' | jsqry
[
  {
    "k1": [
      {
        "k2": [
          9
        ]
      }
    ]
  }
]

Select json data

$ echo '{"k1": [{"k2": [9]}]}' | jq '.k1 | .[0] | .k2 | .[0]'
9

$ echo '{"k1": [{"k2": [9]}]}' | jsqry -1 'k1.k2'
9

Transform json data

$ echo '[{"n": "bob", "v": 100}, {"n": "jim", "v": 101}]' | jq 'map({name: .n, value: .v})'
[
  {
    "name": "bob",
    "value": 100
  },
  {
    "name": "jim",
    "value": 101
  }
]

$ echo '[{"n": "bob", "v": 100}, {"n": "jim", "v": 101}]' | jsqry '{ {name:_.n, value:_.v} }'
[
  {
    "name": "bob",
    "value": 100
  },
  {
    "name": "jim",
    "value": 101
  }
]

Array filters

$ echo '[1, 2]' | jq 'reverse'
[
  2,
  1
]

$ echo '[1, 2]' | jsqry '[::-1]' # python-style!
[
  2,
  1
]

map

$ echo '[{"k1": "v1"}, {"k1": "v2"}]' | jq 'map(.k1)'
[
  "v1",
  "v2"
]

$ echo '[{"k1": "v1"}, {"k1": "v2"}]' | jsqry 'k1'
[
  "v1",
  "v2"
]

map select

$ echo '[{"k1": "v1"}, {"k1": "v2"}]' | jq 'map(select(.k1 == "v1"))'
[
  {
    "k1": "v1"
  }
]

$ echo '[{"k1": "v1"}, {"k1": "v2"}]' | jsqry '[ _.k1=="v1" ]'
[
  {
    "k1": "v1"
  }
]

flatten

$ echo '[[1], [2]]' | jq 'flatten'
[
  1,
  2
]

$ echo '[[1], [2]]' | jsqry '*'
[
  1,
  2
]

array constructor

$ echo '[1, 2, 3]' | jq '[.[0], .[2]]'
[
  1,
  3
]

$ echo '[1, 2, 3]' | jsqry '[ i==0 || i==2 ]' # in jsqry this achieves by filtering on implicit index parameter i
[
  1,
  3
]

Object filters

$ echo '{"k1": "v1", "k2": "v2"}' | jq 'keys'
[
  "k1",
  "k2"
]

$ echo '{"k1": "v1", "k2": "v2"}' | jsqry '{ Object.keys(_) }*'
[
  "k1",
  "k2"
]
$ echo '{"k1": "v1", "k2": "v2"}' | jq 'to_entries'
[
  {
    "key": "k1",
    "value": "v1"
  },
  {
    "key": "k2",
    "value": "v2"
  }
]

$ echo '{"k1": "v1", "k2": "v2"}' | jsqry '{ Object.entries(_) }*' # close analog
[
  [
    "k1",
    "v1"
  ],
  [
    "k2",
    "v2"
  ]
]
$ jq --version
jq-1.5-1-a5b5cbe

$ jsqry --version
0.0.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.