Alper Tovi
Alper Tovi

Reputation: 13

jq to change a specific field value by select

I have a project.json file and its contents look like this:

{
    "packageDirectories": [
        {
            "path": "sfdx-source/unpackaged"
        },
        {
            "path": "sfdx-source/untracked"
        },
        {
            "path": "sfdx-source/zipsc",
            "package": "ZipSC",
            "versionName": "Version 0.1",
            "versionNumber": "0.1.0.NEXT",
            "ancestorId":"oldValue",
            "default": true
        },
        {
            "path": "sfdx-source/unpackaged/open-cti",
            "package": "OpenCTI",
            "versionName": "Ver 0.3",
            "versionNumber": "0.3.0.NEXT",
            "ancestorId": "04t1P000000cB425QAE",
            "default": false
        }
    ],
    "sfdcLoginUrl": "https://login.salesforce.com",
    "sourceApiVersion": "47.0",
    "namespace": "ZAR",
    "packageAliases": {
        "ZAR": "0Ho1P000000XZA4SAO",
        "OpenCTI": "0Ho1P000000X3AvSAO"
    }
}

I want to change the ancestorId field for the packageDirectory objects where default is true. In that case oldValue in the example should become newValue. The output should be as follows. How do I do this with jq on a shell script.

{
    "packageDirectories": [
        {
            "path": "sfdx-source/unpackaged"
        },
        {
            "path": "sfdx-source/untracked"
        },
        {
            "path": "sfdx-source/zipsc",
            "package": "ZipariSC",
            "versionName": "Version 0.1",
            "versionNumber": "0.1.0.NEXT",
            "ancestorId":"newValue",
            "default": true
        },
        {
            "path": "sfdx-source/unpackaged/open-cti",
            "package": "OpenCTI",
            "versionName": "Ver 0.3",
            "versionNumber": "0.3.0.NEXT",
            "ancestorId": "04t1P000000cB425QAE",
            "default": false
        }
    ],
    "sfdcLoginUrl": "https://login.salesforce.com",
    "sourceApiVersion": "47.0",
    "namespace": "ZAR",
    "packageAliases": {
        "ZAR": "0Ho1P000000XZA4SAO",
        "OpenCTI": "0Ho1P000000X3AvSAO",
    }
}

Upvotes: 1

Views: 792

Answers (2)

peak
peak

Reputation: 116750

FYPI, there is a way to achieve the goal using select:

.packageDirectories[] |=
  ((select(.default == true) | .ancestorId = "newValue") // . )

Upvotes: 1

oguz ismail
oguz ismail

Reputation: 50775

You'd use an if-then-else expression for it, not select.

.packageDirectories |= map(
  if .default == true
  then .ancestorId = "newValue"
  else . end
)

demo at jqplay.org

Upvotes: 1

Related Questions