Home > Blockchain >  Reference a json file and pass it as json hash into a json input for a command argument
Reference a json file and pass it as json hash into a json input for a command argument

Time:04-23

I have a json file named "input.json":

{
  "item1": "banana",
  "item2": false
}

and I have a bash command that takes in a json input, which then takes in the hash of the above file content as the value for the "input" key:

executable '{"input": {"item1": "banana", "item2": false}, "option1": "value1", "option2": "value2" }'

How can I pass the json content from input.json file into the command? I have tried:

  • create the one-line json hash from the input.json with jq -c . input.json and pass the hash to a variable, then reference that variable in the command - it did not work (value expected is missing - likely because of the single quote that messed up the reference).

Any help or pointer is appreciated.

CodePudding user response:

You can follow the steps as you had indicated, which should work. Create the base64 content, store it in a variable and pass it to jq

#!/usr/bin/env bash
# Bash script to construct a base64 of a JSON content and passing
# it to an another command

# Create the base64
base=$(jq -c . input.json | base64)

# Create the JSON that stores the above hash
json=$(jq -cn --arg b64 "$base" '{"input": $b64, "option1": "value1", "option2": "value2" }')

# If you want the JSON to be a literal string, use the '@text' filter
# with 'jq'
jsonString=$(jq -cn --arg b64 "$base" '{"input": $b64, "option1": "value1", "option2": "value2" } | @text')

# Pass the contents of either 'json' or 'jsonString', depending on 
# how your executable parses the command line argument
  • Related