Marc
Marc

Reputation: 640

Add text file as an array to json field using jq

I have a JSON file and a text file as shown below :

{
    symbols: null,
    symbols_count : null
}

values.txt

VALUE1
VALUE2
VALUE3

Using jq, I want to add values of values.txt as an array to the symbols field of the json.

symbols_count=$(wc -l < values.txt)

jq ".symbol_count = $symbols_count" < input.json | \
jq --slurpfile symbols values.txt '.symbols_count=$symbols'

The last jq command fails because the values in values.txt are not enclosed by "" .

Is there any way to add double quotes without changing values.txt?

Upvotes: 1

Views: 1418

Answers (2)

peak
peak

Reputation: 116720

  1. jq expects its input to be either valid JSON or raw text, so it would probably be simplest if you could ensure your "JSON file" is valid JSON. See the jq FAQ for further details if that is an issue.

  2. One way to handle values.txt is to use the --rawfile command-line option:

< input.json jq --rawfile text values.txt '
  .symbols = [$text|splits("\n")|select(length>0)]
  | .symbols_count = (.symbols|length)'

Upvotes: 3

L&#233;a Gris
L&#233;a Gris

Reputation: 19555

jq -nR '([inputs | select(length > 0)]) |
{"symbols":., "symbols_count":(. | length)}' values.txt

The jq program with comments:

values2json (chmod +x values2json)

#!/usr/bin/env -S jq -fnR

(
  # Select non-empty input lines as an array
  [ inputs | select( length > 0 ) ]
) |
# Build the object
{
  # with the array created above
  "symbols": .,
  # and the length of the array
  "symbols_count": (. | length)
}

Usage:

./values2json values.txt

Output from sample data:

{
  "symbols": [
    "VALUE1",
    "VALUE2",
    "VALUE3"
  ],
  "symbols_count": 3
}

Upvotes: 1

Related Questions