2

I am trying to find a way to pipe the result of my current script into another command which will leave me with just the last result of the array I get in my select here:

jq -r --arg name "$1" '.packageAliases | to_entries[] | select(.key | startswith($name))' sfdx-project.json 

the sfdx-project.json file is a json file that has a nested JSON called packageAliases, which a script adds new package version numbers and Ids to.

{ "data" : "that", "is" : "not", "really" : "necessary", "packageAliases" : { "package" : "0H0fffff", "[email protected]" : "04t0xxxxxx" } } 

The idea is to select all package aliases of a specific package name, and leave me with the last one, which is the one that I am supposed to use.

When I try to pipe the result I get from my select into last, I get this error: Cannot index object with number

Although I thought that the select() command returns an array (which I also get when I echo the intermediary result)

Placing the last() command anywhere else just leaves me with several null values in an array, but I still do not get the single value I actually need.

What do I need to change about my command to get the last entry from the array that I get out of select()?

2
  • Any chance to see an actual example of a JSON document? That would make it easier to answer. Commented Mar 9, 2022 at 16:10
  • I added an example to the question, though my solution below already did the trick Commented Mar 9, 2022 at 18:53

1 Answer 1

3
jq -r --arg name "$1" 'last(.packageAliases | to_entries[] | select(.key | startswith($name))) 

Wrapping the entire command in last() did the trick, as it was the result of the entire chain of pipes.

2
  • What if the keys are presented in the opposite order in the JSON file, or if there are many partial matches for packages with the same name prefix. Just picking the last one seems rather arbitrary. It would be better to also match the @ after the package name if you want to be at least a bit more certain that what you're getting back from select is something reasonably unique and matches what you're looking for. Also, do you want the key or the value at the end? Commented Mar 9, 2022 at 19:26
  • The @-part is auto-incremented, and the CLI I'm working off of is always appending new versions to the end of the JSON, so in my limited use case - it does not make much of a difference. Commented Mar 9, 2022 at 19:45

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.