Issue
I have below malformed json file. I want to quote the value of email, i.e "[email protected]". How do I go about it? I tried below but doesn't work.
sed -e 's/"email":\[\(.*\)\]/"email":["\1"]/g' sample.json
- where sample.json looks like below
{
"supplementaryData": [
{
"xmlResponse": {
"id": "100001",
"externalid": "200001",
"info": {
"from": "C1022929291",
"phone": "000963586",
"emailadresses": {
"email": [[email protected]
]
}
},
"status": "OK",
"channel": "mobile"
}
}
]
}
Solution
Your code does not work because
[
is not escaped so not treated as a literal- You are using BRE, so capturing brackets will need to be escaped. In its current format, you will need
-E
to use extended functionality - The line does not end with
]
- You did not add the space so there is no match, hence, no replacement.
For your code to work, you can use;
$ sed -E 's/"email": \[(.*)/"email": ["\1"/' sample.json
or
$ sed -E '/\<email\>/s/[a-z@.]+$/"&"/' sample.json
{
"supplementaryData": [
{
"xmlResponse": {
"id": "100001",
"externalid": "200001",
"info": {
"from": "C1022929291",
"phone": "000963586",
"emailadresses": {
"email": ["[email protected]"
]
}
},
"status": "OK",
"channel": "mobile"
}
}
]
}
Answered By - HatLess Answer Checked By - David Goodson (WPSolving Volunteer)