dogman
dogman

Reputation: 79

Add a single object to an array

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"

Upvotes: 0

Views: 134

Answers (3)

Weeble
Weeble

Reputation: 17960

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.

Upvotes: 0

chepner
chepner

Reputation: 532208

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.

Upvotes: 1

Daniel
Daniel

Reputation: 2025

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

Upvotes: 0

Related Questions