Home > front end >  How to create json body using jq from variables, while preserving type
How to create json body using jq from variables, while preserving type

Time:08-27

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 }

CodePudding user response:

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}' )
  • Related