Create JSON file using jq

Viewed 35349

I'm trying to create a JSON file by executing the following command:

jq --arg greeting world '{"hello":"$greeting"}' > file.json

This command stuck without any input. While

jq -n --arg greeting world '{"hello":"$greeting"}' > file.json

doesn't parse correctly. I'm just wondering is really possible to create a JSON file.

3 Answers

$ARGS provides access to named (--arg name value) and positional (--args one two three) arguments from the jq command line, and allows you to build up objects easily & safely.

Named arguments:

$ jq -n '{christmas: $ARGS.named}' \
  --arg one 'partridge in a "pear" tree' \
  --arg two 'turtle doves'

{
  "christmas": {
    "one": "partridge in a \"pear\" tree",
    "two": "turtle doves"
  }
}

Positional arguments:

$ jq -n '{numbers: $ARGS.positional}' --args 1 2 3

{
  "numbers": [
    "1",
    "2",
    "3"
  ]
}

Note you can access individual items of the positional array, and that the named arguments are directly available as variables:

jq -n '{first: {name: $one, count: $ARGS.positional[0]}, all: $ARGS}' \
  --arg one 'partridge in a "pear" tree' \
  --arg two 'turtle doves' \
  --args 1 2 3

{
  "first": {
    "name": "partridge in a \"pear\" tree",
    "count": "1"
  },
  "all": {
    "positional": [
      "1",
      "2",
      "3"
    ],
    "named": {
      "one": "partridge in a \"pear\" tree",
      "two": "turtle doves"
    }
  }
}
Related