Home > Net >  jq does not show null output
jq does not show null output

Time:05-18

I have the following code in the command line script:

output_json=$(jq -n \
                 --argjson ID "${id}" \
                 --arg Title "${title}" \
                 --argjson like "\"${like}\"" \
                '$ARGS.named')

I put the id, title and like variables into the jq. I get the following output:

[
  {
    "ID": 6,
    "Title": "ABC",
    "like": ""
  },
  {
    "ID": 22,
    "Title": "ABC",
    "like": "Yes"
  }
]

But, I am trying to get the output in the following format, i.e. with null:

[
  {
    "ID": 6,
    "Title": "ABC",
    "like": null
  },
  {
    "ID": 22,
    "Title": "ABC",
    "like": "Yes"
  }
]

I don't quite get it is it possible to do this in general, or is it a problem with my jq command?

And as far as I understood "like": "" is not the same as "like": null. I am also a little confused now, and do not really understand what is the correct choice to use.

CodePudding user response:

By using --argjson you need to provide valid JSON-encoded argument, thus if you want to receive null the value needs to be literally null. Your solution, however, adds quotes around it, so it can never be evaluated to null. (Also, it will only be a valid JSON string if it follows the JSON encoding for special characters such as the quote characters itself).

If you want to have a JSON string in the regular case, and null in the case where it is empty, import the content of ${like} as string using --arg and without the extra quotes (just as you do with ${title}), then use some jq logic to turn the empty string into null. An if statement would do, for example:

like=
jq -n --arg like "${like}" '{like: (if $like == "" then null else $like end)}'
{
  "like": null
}
  • Related