diff --git a/docs/content/3.manual/manual.yml b/docs/content/3.manual/manual.yml index 26c367a4..ea0514ed 100644 --- a/docs/content/3.manual/manual.yml +++ b/docs/content/3.manual/manual.yml @@ -190,7 +190,15 @@ sections: This option passes a value to the jq program as a predefined variable. If you run jq with `--arg foo bar`, then `$foo` is - available in the program and has the value `"bar"`. + available in the program and has the value `"bar"`. Note that + `value` will be treated as a string, so `--arg foo 123` will + bind `$foo` to `"123"`. + + * `--argjson name JSON-text`: + + This option passes a JSON-encoded value to the jq program as a + predefined variable. If you run jq with `--argjson foo 123`, then + `$foo` is available in the program and has the value `123`. * `--argfile name filename`: diff --git a/main.c b/main.c index 8ebdb9fc..682c7aa3 100644 --- a/main.c +++ b/main.c @@ -39,6 +39,7 @@ static void usage(int code) { fprintf(stderr, "\t -r\t\toutput raw strings, not JSON texts;\n"); fprintf(stderr, "\t -R\t\tread raw strings, not JSON texts;\n"); fprintf(stderr, "\t --arg a v\tset variable $a to value ;\n"); + fprintf(stderr, "\t --argjson a v\tset variable $a to JSON value ;\n"); fprintf(stderr, "\t --argfile a f\tset variable $a to JSON texts read from ;\n"); fprintf(stderr, "\tSee the manpage for more options.\n"); exit(code); @@ -307,6 +308,23 @@ int main(int argc, char* argv[]) { i += 2; // skip the next two arguments if (!short_opts) continue; } + if (isoption(argv[i], 0, "argjson", &short_opts)) { + if (i >= argc - 2) { + fprintf(stderr, "%s: --argjson takes two parameters (e.g. -a varname text)\n", progname); + die(); + } + jv v = jv_parse(argv[i+2]); + if (!jv_is_valid(v)) { + fprintf(stderr, "%s: invalid JSON text passed to --argjson\n", progname); + die(); + } + jv arg = jv_object(); + arg = jv_object_set(arg, jv_string("name"), jv_string(argv[i+1])); + arg = jv_object_set(arg, jv_string("value"), v); + program_arguments = jv_array_append(program_arguments, arg); + i += 2; // skip the next two arguments + if (!short_opts) continue; + } if (isoption(argv[i], 0, "argfile", &short_opts)) { if (i >= argc - 2) { fprintf(stderr, "%s: --argfile takes two parameters (e.g. -a varname filename)\n", progname);