Reputation: 434
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
{
"supplementaryData": [
{
"xmlResponse": {
"id": "100001",
"externalid": "200001",
"info": {
"from": "C1022929291",
"phone": "000963586",
"emailadresses": {
"email": [[email protected]
]
}
},
"status": "OK",
"channel": "mobile"
}
}
]
}
Upvotes: 0
Views: 297
Reputation: 133518
With your shown samples, please try following awk
code. Written and tested in GNU awk
. Making RS
as NULL and using awk
's function named match
where I am using regex (.*)(\n[[:space:]]+"emailadresses": {\n[[:space:]]+"email": \[)([^\n]+)(.*)
to get required output which is creating 4 capturing groups which are 4 different values into array named arr
(GNU awk
's functionality in match
function to save captured values into arrays) and then printing values as per requirement(adding "
before and after email address value, which is 3rd element of arr
OR 3rd capturing group of regex).
awk -v RS= '
match($0,/(.*)(\n[[:space:]]+"emailadresses": {\n[[:space:]]+"email": \[)([^\n]+)(.*)/,arr){
print arr[1] arr[2] "\"" arr[3] "\"" arr[4]
}
' Input_file
Upvotes: 2
Reputation: 11227
Your code does not work because
[
is not escaped so not treated as a literal-E
to use extended functionality]
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"
}
}
]
}
Upvotes: 3