Home > Mobile >  how can I build bash hyperlink strings from json fields?
how can I build bash hyperlink strings from json fields?

Time:05-19

I am getting some JSON data from the NYTimes API. I can get things to this form:

"results": [
{
  "headline": "such and such",
  "url": "http://such.and.such.com",
  ...
},
{
  "headline": "so and so",
  "url": "http://so.and.so.com",
  ...
},
...
]

I want to echo 1 string for every object in the array, so that the string text displays the headline, and the string is clickable to the url.

I know how I want the string to be built:

echo -e "\e]8;;$URL\a$TITLE\e]8;;\a"

I can't figure out how to use jq to populate those variable portions of the string.

> echo $RESULTS | jq '.results[] | "\e]8;;\(.url)\a\(.title)\e]8;;\a"'
jq: error: Invalid escape at line 1, column 4 (while parsing '"\e"') at <top-level>, line 1:
.results[] | "\e]8;;\(.url)\a\(.title)\e]8;;\a"
jq: error: Invalid escape at line 1, column 4 (while parsing '"\a"') at <top-level>, line 1:
.results[] | "\e]8;;\(.url)\a\(.title)\e]8;;\a"
jq: error: Invalid escape at line 1, column 4 (while parsing '"\e"') at <top-level>, line 1:
.results[] | "\e]8;;\(.url)\a\(.title)\e]8;;\a"
jq: error: Invalid escape at line 1, column 4 (while parsing '"\a"') at <top-level>, line 1:
.results[] | "\e]8;;\(.url)\a\(.title)\e]8;;\a"
jq: 4 compile errors

CodePudding user response:

\e and \a are not valid in a JSON string; to encode the escape and bell control characters, you need to use \u001b and \u0007 respectively. You probably also want use the -r option to jq to make it output raw strings (rather than JSON-encoded).

I would also strongly recommend double-quoting shell variable references (to avoid weird effects from word splitting and wildcard expansion), and using lower- or mixed-case variable names to avoid conflicts with the many all-caps names that have special meanings or functions.

So something like this:

echo "$results" | jq -r '.results[] | "\u001b]8;;\(.url)\u0007\(.title)\u001b]8;;\u0007"'

Or, in bash (but not all other shells) you can use a here-string instead of echo:

jq -r '.results[] | "\u001b]8;;\(.url)\u0007\(.title)\u001b]8;;\u0007"' <<<"$results"
  • Related