Home > Software design >  Replace only value in json while ignoring keys with javascript
Replace only value in json while ignoring keys with javascript

Time:11-10

i have this json: {"agent": "Teste","obs": "obs 2 in other obs","id": 4,"queue": "Suply","name":"Other"}

I need this with Regex {"agent": "Teste","obs": "<b>obs</b> 2 in other <b>obs</b>","id": 4,"queue": "Suply","name":"Other"}

I fail in replace because the key "obs" is replaced too.

CodePudding user response:

You can use this regex:

/obs(?!":)/g

It uses the negative lookahead assertion.

const json = JSON.stringify({"agent": "Teste","obs": "obs 2 in other obs","id": 4,"queue": "Suply","name":"Other"})

console.log(json.replace(/(obs)(?!":)/g, '<b>$1</b>'))

CodePudding user response:

This uses a regex with 2 capture groups. The first capture group is replaced with <b> and </b> around it. Then the second capture group is replaced. Because the second capture group excludes the colon, the keys are not altered. There are two period characters as one of them is to take into account the forward slash introduced by JSONStringify() and the other is for the quote mark after a key.

const JSONString = JSON.stringify('{"agent": "Teste","obs": "obs 2 in other obs","id": 4,"queue": "Suply","name":"Other"}');

const re = /(obs)(..[^:])/g;

let newJSONString = JSONString.replace(re, '<b>$1</b>$2');

newObject = JSON.parse(newJSONString);

console.log(newObject);

  • Related