Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SED command – Replace a key and value pair in JSON file – key name is similar to all Array objects

Goal to replace – "text": "V01_08_17", with "text": "Customized String", in below json file with sed

File.json as mentioned above

{
  "type": "textList",
  "texts": [
    {
      "type": "textElement",
      "text": "V01_08_17",
      "aliasName": "versionScreen"
    },
    {
      "type": "textElement",
      "text": "V01_08_10_XYZ",
      "aliasName": "VersionXYZ"
    },
    {
      "type": "textElement",
      "text": "V01_08_20_ABC",
      "aliasName": "VersionABC"
    }
  ],
  "name": "Configuration",
  "observe": false,
  "revision": {
    "type": "Revision",
    "revisionNr": "0.0"
  },
  "version": "0.0.74"
}

Tried different combinations with sed but not able to replace only the specific array object value.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Using text-processing tools like awk or sed for structured data like JSON has its limits. They can only process the textual representation of the data, not it’s logical structure, and as such you’d have to write a full JSON processor in them to have a robust solution. Better use one that is already written, like jq for example:

jq --arg from "V01_08_17" --arg to "Customized String" \
  '(.texts[].text | select(. == $from)) = $to' file.json
{
  "type": "textList",
  "texts": [
    {
      "type": "textElement",
      "text": "V01_08_17",
      "aliasName": "versionScreen"
    },
    {
      "type": "textElement",
      "text": "V01_08_10_XYZ",
      "aliasName": "VersionXYZ"
    },
    {
      "type": "textElement",
      "text": "V01_08_20_ABC",
      "aliasName": "VersionABC"
    }
  ],
  "name": "Configuration",
  "observe": false,
  "revision": {
    "type": "Revision",
    "revisionNr": "0.0"
  },
  "version": "0.0.74"
}

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading