Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create JSON file using jq

Tags:

json

jq

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.

like image 534
Mazzy Avatar asked Aug 02 '17 19:08

Mazzy


People also ask

Can jq create JSON?

The safest way to create JSON on the command line is through using a tool that constructs it for you as jq does.

What is jq for JSON?

jq is a lightweight and flexible command-line JSON processor. If you are a command line addict, you will like the official description. jq is like sed for JSON data – you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text.


2 Answers

So your code doesn't work because included the variable inside double quotes which gets treated as string. That is why it is not working

As @Jeff Mercado, pointed out the solution is

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

About the - in a name. This is actually possible. But as of now this is not available in released version of jq. If you compile the master branch of jq on your system. There is a new variable called $ARGS.named which can be used to access the information.

I just compiled and check the below command and it works like a charm

./jq -n --arg name-is tarun '{"name": $ARGS.named["name-is"]}'
{
  "name": "tarun"
}
like image 186
Tarun Lalwani Avatar answered Sep 21 '22 09:09

Tarun Lalwani


$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"
    }
  }
}
like image 32
rcoup Avatar answered Sep 22 '22 09:09

rcoup