2

Given the following JSON file (sample.json)

{
  "api": "3.0.0",
  "data": {
    "description": "something",
    "title": "hello",
    "version": "1.0",
    "app": {
      "name": "abc",
      "id": "xyz"
    }
  }
}

I wish to add the following JSON object at root level to the file above:

{
  "heading": {
    "user": ["$username"]
  }
}

Where $username is a Bash variable.

Is there a better way to achieve this than the following?

blob=$(jq -n --arg foo API_NAME '{"heading": {"user": [env.username]}}')

jq --argjson obj "$(echo $blob)" '. + $obj' < sample.json

1

1 Answer 1

2

Just move what you create as blob directly into the other filter, ending up with just one jq call:

jq --arg username "$username" '. + {heading: {user: [$username]}}' sample.json
Sign up to request clarification or add additional context in comments.

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.