0

So I have this json structure:

{
  "dog": [
    {
      "name": "sam",
      "age": "2"
    },
    {
      "name": "billy",
      "age": "5"
    }
  ]
}

I've found that .dog[1] will return me the first object but not in the dog:[] array.

{
  "name": "billy",
  "age": "5"
}

and .[] |= .[$i] gives me an object:

{
  "dog": {
    "name": "billy",
    "age": "5"
  }
}

What I want is:

{
  "dog": [
    {
      "name": "sam",
      "age": "2"
    }
  ]
}

I plan to use this in a bash script, and write out to multiple files like:

jq -r --argjson i "$i" '.[] |= .[$i]' "$1"

1
  • Do you need the array slice? .[1:2] Commented Aug 25, 2021 at 10:06

3 Answers 3

1

Instead of an integer index, use a slice. (Also, the array is 0-indexed, not 1-indexed.)

$ jq --argjson i 0 '{dog: .dog[$i:$i+1]}' < tmp.json
{
  "dog": [
    {
      "name": "sam",
      "age": "2"
    }
  ]
}

As you are asking for an object, not a string, the -r option doesn't do anything.

Sign up to request clarification or add additional context in comments.

Comments

0

Try

jq --argjson i 2 '.dog|=[.[$i-1]]'

The .dog|=[.[$index]] part modifies just the array dog and replaces it with an array of just the item at position $index. This has the benefit of preserving anything else that might be in the top-level object. We use $i-1 since you indicate you want to provide 1-based indices as input.

1 Comment

I had wondered about that. As it was already in dog that seems more efficient, rather than re-creating dog. As it's being used in a bash script, the counter is already initialized to 0, so jq --argjson i 1 '.dog|=[.[$i]]' will work nicely too.
0

JSON arrays starts from zero. you should use index 0 instead of 1: .dog[0]

4 Comments

I know JSON originated in Javascript, but there's no reason to mention it here. Arrays in JSON (like in many languages) are zero-indexed.
@chepner I did adress js since it's a javascript object notation but you're correct, jq is for parsing JSON, and the question is not related to js. fixed :)
Regardless, this doeesn't answer at least half of the question - how to keep the structure of the input.
@Weeble He had the correct structure, his only issue was the indexing.

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.