1

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?

2 Answers 2

3
  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)'
Sign up to request clarification or add additional context in comments.

Comments

1
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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.