Skip to content

Instantly share code, notes, and snippets.

@DrJume
Last active April 17, 2020 02:27
Show Gist options
  • Save DrJume/e3732b4b28a5de1b7173a8053ed5fbdc to your computer and use it in GitHub Desktop.
Save DrJume/e3732b4b28a5de1b7173a8053ed5fbdc to your computer and use it in GitHub Desktop.
My collection of cool snippets
Pipe command output to a logging service
apimon -c apimon.yml |      # Prints JSON messages
  while IFS= read -r json   # Read line by line. $json holds the line content
  do
    # Send JSON over a HTTP Post request
    echo $json | curl -H "Content-Type: application/json" -X POST -d @- http://yourloggingserver:4321
  done
Stringify JSON
echo $json | sed -E 's/"/\\"/g'     # Escapes all " to \"
JSON append key-value pair
echo $json |
  # Replace the ending of a JSON string (closing curly brace before line end) with an
  # added key-value pair and new closing curly brace. 
  # Replace key with any string. value is a awk variable. It is concatenated without 
  # any special operator: "foo"var"bar".
  awk -v value=$(echo 'foo') '{gsub(/}$/,",\"key\":\""value"\"}"); print}'

If you wish to insert an escaped JSON string as a value:

echo $json |
  # You need to double escape the JSON!
  awk -v value=$(echo $some_other_json | sed -E 's/"/\\\\"/g') '{gsub(/}$/,",\"key\":\""value"\"}"); print}'

Take a look at jq if you like to manipulate JSON a lot easier:

echo $json | jq '. + { key: "value" }'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment