Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I was wondering, "Why not pipe output to JQ" up until I read this:

> A not insignificant amount of people on stackoverflow etc have problems to send correct JSON with curl and to get the quoting done right, as json uses double-qoutes by itself and shells don't expand variables within single quotes etc.

It's about sanitized inputs.



> It's about sanitized inputs.

Less sanitized and more correctly formatted. Writing literal JSON by hand at the CLI is not fun.


That is why you use jq --arg for the input instead of crafting it by string concatenation.

    data=$(jq -n \
            --arg title 'what"ever' \
            --arg endpoint 'foo"bar' \
            '{
            "title": $title,
            "endpoint": $endpoint,
            "enabled": true
    }')


I use jq exclusively for parsing output. Didn't know you could craft JSON with jq as well. Thanks for the tip!


If I really had to get some JSON into a Bash script, and I couldn't just stick it in a file, I'd probably use a "heredoc" something like this:

    $ my_json="$(cat <<EOF
    > {
    >   "foo": "bar",
    >   "baz": 42
    > }
    > EOF
    > )"
    $ echo "$my_json"
    {
      "foo": "bar",
      "baz": 42
    }
But I definitely didn't remember how to handle the closing paren and closing quote correctly, and I had to google for an example just now. So I'm not allowed to say this is easy to remember :)


Random bit of trivia: on ksh you can do

  foo="$(cat <<EOF)"
  whatever
  EOF
This is left undefined in the POSIX standard and bourne shells don't allow it.


Fwiw, here docs solve both of these; they expand variables and allow double quotes and braces.


They don't solve escaping quotes inside the variables you paste into your JSON.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: