Skip to content

Instantly share code, notes, and snippets.

@nicopace
Created July 2, 2017 10:29
Show Gist options
  • Save nicopace/834dd124ed95a3f89e8a1f446816247d to your computer and use it in GitHub Desktop.
Save nicopace/834dd124ed95a3f89e8a1f446816247d to your computer and use it in GitHub Desktop.
#!/bin/sh
# This will convert any text passed through stdin to a JSON-valid string
# Based on https://stackoverflow.com/a/11495576/2399665
JSON_TOPIC_RAW=`cat`
JSON_TOPIC_RAW=${JSON_TOPIC_RAW//\\/\\\\} # \
JSON_TOPIC_RAW=${JSON_TOPIC_RAW//\//\\\/} # /
JSON_TOPIC_RAW=${JSON_TOPIC_RAW//\'/\\\'} # ' (not strictly needed ?)
JSON_TOPIC_RAW=${JSON_TOPIC_RAW//\"/\\\"} # "
JSON_TOPIC_RAW=${JSON_TOPIC_RAW// /\\t} # \t (tab)
JSON_TOPIC_RAW=${JSON_TOPIC_RAW//
/\\\n} # \n (newline)
JSON_TOPIC_RAW=${JSON_TOPIC_RAW//^M/\\\r} # \r (carriage return)
JSON_TOPIC_RAW=${JSON_TOPIC_RAW//^L/\\\f} # \f (form feed)
JSON_TOPIC_RAW=${JSON_TOPIC_RAW//^H/\\\b} # \b (backspace)
echo JSON_TOPIC_RAW
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment