YQ/JQ special characters query convertor

1k views Asked by At

I am using yq together with jq and as I have learned you need to "escape" special characters in keys to quotes and brackets. I would like to query the data using the pure dot syntax .cars.big-trucks but I was unable to find any tool that would do the conversion for me.

My ideal usage would be:

query=$(jq-query-convert ".cars.big-trucks")
yq -r $query cars.yaml

Any ideas? Thanks

Example yaml file:

%YAML 1.1
---

cars:
    big-trucks: 42

For jq users an example json would be:

{
 "cars": {
  "big-trucks": 42
 }
}

queried by

cat cars.json | jq "$q"
1

There are 1 answers

0
lukashino On

Well I came up with this python3 one-liner that serves my intentions so far but if anyone know more robust solutions I am happy to accept it.

python3 -c 'from sys import argv; print("." + argv[1].replace(".", "\"][\"")[2:] + "\"]")' ".cars.big-trucks"

returns
.["cars"]["big-trucks"]