Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create json body using jq from variables, while preserving type

I am creating a simple bash script and am trying to build a json body using jq

name='"john"'
objects='[]'
count='1'

data=$( jq -n \
            --arg na $name \
            --arg ob $objects \
            --arg ct $count \
            '{name: $na, objects: $ob, count: $ct}' )

When I echo data, I get
{ "name": "john", "objects": "[]", "count": "1" }

However, the objects and count values are strings.
Instead I want, { "name": "john", "objects": [], "count": 1 }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you’re sure that all the variables contain valid JSON expressions, you can use --argjson instead of --arg:

#!/usr/bin/env bash

name='"john"'
objects='[]'
count='1'

# Note quoting the variables to prevent issues with unwanted expansion
data=$( jq -n \
            --argjson na "$name" \
            --argjson ob "$objects" \
            --argjson ct "$count" \
            '{name: $na, objects: $ob, count: $ct}' )

printf "%s\n" "$data"

outputs

{
  "name": "john",
  "objects": [],
  "count": 1
}

Alternatively, you can use fromjson in the jq expression:

data=$( jq -n \
            --arg na "$name" \
            --arg ob "$objects" \
            --arg ct "$count" \
            '{name: $na|fromjson, objects: $ob|fromjson, count: $ct|fromjson}' )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading