Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR SHELL

modify JSON values in place with jq

#!/bin/bash

if [ $# -lt 3 ]; then 
  echo ""
  echo "This script requires jq to be installed." 
  echo "It will add or modify the specified key and value in the JSON file."
  echo "Three arguments required: (1) key, (2) value, (3) json file to modify,"
  echo "and optionally a 4th argument s (for string) if the value is a string and should be wrapped in double quotes e.g."
  echo ""
  echo "===================================="
  echo ""
  echo "In the following examples, Modality is the key, test.json is the file"
  echo ""
  echo "To add/modify a number value, e.g.," 
  echo "jadd Modality 3 test.json"
  echo ""
  echo "To add/modify a boolean, e.g., "  
  echo "jadd Modality true test.json"
  echo ""
  echo "To add/modify an array of numbers, wrap the array in single quotes, e.g.,:"
  echo "jadd Modality '[1,3,5]' test.json"
  echo ""
  echo "To add/modify an array of strings, wrap the array in single quotes and put the strings in double quotes, e.g.,"
  echo  'jadd Modality '['"a"','"b"','"c"']' test.json'
  echo ""
  echo "To add/modify a string, add the 4th argument, s:"
  echo "jadd Modality MRI jq_test.json s"
  echo ""
  
  echo "======================="
  exit 1 
elif [ $# -eq 3 ]; then 
  key=$1
  value=$2
  file=$3
  # Add number or boolean or array using --argjson
  # echo "Three arguments key=$key; value=$value; file=$file"
  #  jq '."'"$key"'"= '$value'' $file > tmp.$$.json && mv tmp.$$.json $file
  jq --argjson val "$value" '."'"$key"'"=$val' "${file}" > tmp.$$.json && mv tmp.$$.json $file
elif [ $# -eq 4 ]; then 
  key=$1
  value=$2
  file=$3
  string=$4
  # Add a string using --arg
  # echo "Four arguments key=$key; value=$value; file=$file; string=$string"
  # jq '."'"$key"'"= "'"$value"'"' $file > tmp.$$.json && mv tmp.$$.json $file
  jq --arg val "$value" '."'"$key"'"=$val' "${file}" > tmp.$$.json && mv tmp.$$.json $file
fi
 
PREVIOUS NEXT
Tagged: #modify #JSON #values #place #jq
ADD COMMENT
Topic
Name
3+7 =