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.
>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"
}