jsonbashjq

Create JSON file using 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.


Solution

  • 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"
    }