skip to Main Content

Say I have this JSON:

{
  "lunch": {
    "time": "11 am",
    "food": {
      "is_pizza": true
    }
  },
  "snacks": [
    {
      "time": "2 pm",
      "food": {
        "is_pizza": true
      }
    },
    {
      "time": "3:30 pm",
      "food": {
        "is_pizza": true
      }
    }
  ],
  "dinner": {
    "time": "6 pm",
    "food": {
      "is_pizza": true
    }
  }
}

Now I want to go through and wherever I see "food" object, add a the same key-value pair:

{
  "lunch": {
    "time": "11 am",
    "food": {
      "is_pizza": true,
      "extra_cheese": true
    }
  },
  "snacks": [
    {
      "time": "2 pm",
      "food": {
        "is_pizza": true,
        "extra_cheese": true
      }
    },
    {
      "time": "3:30 pm",
      "food": {
        "is_pizza": true,
        "extra_cheese": true
      }
    }
  ],
  "dinner": {
    "time": "6 pm",
    "food": {
      "is_pizza": true,
      "extra_cheese": true
    }
  }
}

How can I do that in jq?

2

Answers


  1. here is how you can do this using the jq command line tool

    cat input.json | jq '. | walk(if type == "object" and has("food") then .food += {"extra_cheese": true} else . end)'
    
    Login or Signup to reply.
  2. Using walk would be one way:

    walk(select(objects | has("food")).food.extra_cheese = true)
    

    Demo

    Using .. would be another:

    (.. | objects | select(has("food"))).food.extra_cheese = true
    

    Demo


    If you wanted to import and add the object {"extra_cheese": true} from outside, use the --argjson option:

    jq --argjson new '{"extra_cheese": true}' '‌... .food += $new' file.json
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search