0
[
  {
    "username": "new",
    "attributes": [
      {
        "name": "attr1",
        "value": "value1"
      },
      {
        "name": "attr2",
        "value": "value2"
      }
    ]
  },
  {
    "username": "new2",
    "attributes": [
      {
        "name": "attr2",
        "value": "value3"
      },
      {
        "name": "attr1",
        "value": "value4"
      }
    ]
  }
]

I have a json as above. From this json, I would like to get the following:

[
  {
    "username": "new",
    "value": "value1"
  },
  {
    "username": "new2",
    "value": "value4"
  }
]

The value I want to have in this object is the value for attribute named attr1. How I can achieve this with jq?

Edit: Fixed errors in the qn. I have tried

echo $USERS | jq ['.[] | {username:username, value: jq '.attributes[]  | select(.name == "attr1") | .value'}'];

where $USERS contains the json data

6
  • 1
    The shown expected output is inconsistent with the stated requirements. Please fix and also show at least one attempt you’ve made to solve the problem. As they say, SO is not a free programming service. Commented Aug 31, 2020 at 7:33
  • Why is Value lowercased? Commented Aug 31, 2020 at 7:47
  • Should value4 be value3? Commented Aug 31, 2020 at 8:14
  • if attr1 is always present you can use map({ username, value: .attributes | map(select(.name == "attr1"))[0].value }) Commented Aug 31, 2020 at 9:18
  • @nanoticket - What if attr1 does not occur in the array, or occurs more than once? Commented Aug 31, 2020 at 9:34

1 Answer 1

1
 map({ username,
       value: first(.attributes[]
                    | select(.name == "attr1")
                    | .value) })
Sign up to request clarification or add additional context in comments.

1 Comment

@dan1st - It's just four lines of very straightforward code, so there's really nothing more to be said other than perhaps: please check the jq tutorial if you're unfamiliar with jq, and please check the jq manual if you're unfamiliar with map or select.

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.