Vitalis
Vitalis

Reputation: 434

Sed to add quotes around json text following a specific json key

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

Answers (2)

RavinderSingh13
RavinderSingh13

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

sseLtaH
sseLtaH

Reputation: 11227

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

Upvotes: 3

Related Questions