]> granicus.if.org Git - jq/commitdiff
Add --argjson, fix #648
authorNicolas Williams <nico@cryptonector.com>
Fri, 12 Dec 2014 22:40:07 +0000 (16:40 -0600)
committerNicolas Williams <nico@cryptonector.com>
Fri, 12 Dec 2014 22:40:07 +0000 (16:40 -0600)
docs/content/3.manual/manual.yml
main.c

index 26c367a4ad843e9e954dd9b595c2151b8d415c1b..ea0514ed835e4e60c2b66d086e3c4b3f195ffc02 100644 (file)
@@ -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 8ebdb9fc0f90370f861c69a13696156b5c26a14d..682c7aa38c582611d746ffa00ed1c1c126b2c0a5 100644 (file)
--- 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 <v>;\n");
+  fprintf(stderr, "\t --argjson a v\tset variable $a to JSON value <v>;\n");
   fprintf(stderr, "\t --argfile a f\tset variable $a to JSON texts read from <f>;\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);