DEV Community

Cover image for Dasel - jq for yaml json and toml
Ruan Bekker
Ruan Bekker

Posted on

Dasel - jq for yaml json and toml

I stumbled upon a great tool called Dasel which enables you to query and modify data structures using selector strings.

I was working on a Rust project and wanted a way to query Toml files, similar to how you would use jq for json data.

Dasel was exactly what I was looking for.

Installation

If you are on Mac you can use homebrew to install:

brew install dasel
Enter fullscreen mode Exit fullscreen mode

If you are on Linux you can install Dasel using:

wget https://github.com/TomWright/dasel/releases/download/v2.1.2/dasel_linux_amd64
install -o root -g root -m 0755 dasel_linux_amd64 /usr/bin/dasel
Enter fullscreen mode Exit fullscreen mode

YAML

For the first demonstration we will use the following deployment.yaml file:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - image: nginx:1.15.0
        name: nginx
        ports:
        - containerPort: 80
Enter fullscreen mode Exit fullscreen mode

Let's say we wanted to query the number of replicas:

$ dasel -f deployment.yaml -r yaml '.spec.replicas'                                                     
2
Enter fullscreen mode Exit fullscreen mode

If we wanted to view the image:

$ dasel -f deployment.yaml -r yaml '.spec.template.spec.containers.[0].image'
nginx:1.14.2
Enter fullscreen mode Exit fullscreen mode

We can use put to query and write information back to the yaml file. In this example we will update the container image:

dasel put -t string -v nginx:1.15.0 -f deployment.yaml -r yaml '.spec.template.spec.containers.[0].image'
Enter fullscreen mode Exit fullscreen mode

To view if the image was updated:

dasel -f deployment.yaml -r yaml '.spec.template.spec.containers.[0].image'                           
nginx:1.15.0
Enter fullscreen mode Exit fullscreen mode

TOML

For toml configuration, lets say the file we are working with is Cargo.toml:

[package]
name = "helloworld"
version = "0.1.0"
edition = "2021"
Enter fullscreen mode Exit fullscreen mode

To view the name:

$ dasel -f Cargo.toml -r toml '.package.name'
helloworld
Enter fullscreen mode Exit fullscreen mode

JSON

For JSON data, we can query it like this:

$ echo '{"names": [{"name":{"first":"Tom","last":"Wright"}}]}' | dasel -r json 'names.[0].name.first'
Tom
Enter fullscreen mode Exit fullscreen mode

We can also use the filter function:

$ echo '{"names": [{"name":"Tom","last":"Wright"},{"name":"John","last":"Wrong"}]}' | dasel -r json 'names.all().filter(name)'
Enter fullscreen mode Exit fullscreen mode

Thank You

Thanks for reading.

Top comments (0)