3

Here is my sample test.json file

[
    {
        "description": "Some description",
        "name": "Some name",
        "summary": "Some summary. "
    },
    {
        "description": "Some description",
        "name": "Some name",
        "summary": "Some summary. "
    },
    {
        "description": "Some description",
        "name": "Some name",
        "summary": "Some summary. "
    }
]

Here is the bash script

declare -A values=( )
while IFS= read -r value; do
  echo "Read  $value" >&2
  #echo $value | curl -d @- -H "Content-Type: application/json" https://example.com/api/foo
done < <(jq -r '.[]' <$1)

This is the output that I get

Read {
Read    "description": "Some description",
Read    "name": "Some name",
Read    "summary": "Some summary. "
Read }
Read {
Read    "description": "Some description",
Read    "name": "Some name",
Read    "summary": "Some summary. "
Read }
Read {
Read    "description": "Some description",
Read    "name": "Some name",
Read    "summary": "Some summary. "
Read }

I want to use the JSON objects in the file, to POST data to an API using curl. I would expect the loop to run three times.

How do I get entire JSON object (resulting in the loop running 3 times) instead of outputting every single line from the test.json file?

0

1 Answer 1

7

Use jq -c, to emit each result on a separate line. Don't use -r when your intended output is JSON, not a raw string.

I've also added some quotes below, which were missing from your code:

# for readability, factored out
args=( -d @- -H "Content-Type: application/json"  )

while IFS= read -r value; do
  echo "Read  $value" >&2
  curl "${args[@]}" https://example.com/api/foo <<<"$value"
done < <(jq -c '.[]' <"$1")
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome! Thank you so much.

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.