Home > Software engineering >  Find and append an string in json file using jq
Find and append an string in json file using jq

Time:05-11

I've a Json file meta.json with the below content and I want to do find and append operation in the below json file using jq filter. For example the below json value of name is demo so, append an string to it like -test so the final value will be demo-test

{
  "version": "2.2.0",
  "vname": "tf",
  "data": {
    "name": "demo",
    "udn": {
      "description": "The `main` tf in this template creates a resource`. "
    }
  }
}

The updated json file should contain the data like below

{
  "version": "2.2.0",
  "vname": "tf",
  "data": {
    "name": "demo-test",
    "udn": {
      "description": "The `main` tf in this template creates a resource`. "
    }
  }
}

Does JQ filter supports this? how we can do this?

CodePudding user response:

Using jq

$ jq '.data.name |= .   "-test"' meta.json
{
  "version": "2.2.0",
  "vname": "tf",
  "data": {
    "name": "demo-test",
    "udn": {
      "description": "The `main` tf in this template creates a resource`. "
    }
  }
}

Using sed

$ sed '/\<name\>/s/[[:punct:]]\ $/-test&/' meta.json
{
  "version": "2.2.0",
  "vname": "tf",
  "data": {
    "name": "demo-test",
    "udn": {
      "description": "The `main` tf in this template creates a resource`. "
    }
  }
}
  • Related