简体   繁体   中英

Replace a special part of a JSON string

I have a JSON object called users like this:

[{"givenName":"helen","sn":"brown","phone":"44512","details":"512"},{{"givenName":"John","sn":"Doe","phone":"44600","details":"512"}]

I apply json.stringify method to convert this JavaScript object to a JSON string. Then, I use replace to replace 512 value with active . Here is my code to implement this:

var jsonUsers = JSON.stringify(users).replace(/512/g, 'active');

The problem is that when I use this code, it replaces all 512 with active (for example in my example, it changes details values and also it changes the phone value of the first person with something like 44active ), but I want to apply this replacement only on the values of the details key, not on whole of the string (for example I don't want to check and replace the value of the phone ). How can I do this?

Don't try to replace parts of a JSON. Fix it while it's an object instead.

 const arr = [{"givenName":"helen","sn":"brown","phone":"44512","details":"512"},{"givenName":"John","sn":"Doe","phone":"44600","details":"512"}]; for (const item of arr) { if (item.details === '512') { item.details = 'active'; } } console.log(JSON.stringify(arr));

const users = [{"givenName":"helen","sn":"brown","phone":"44512","details":"512"},{"givenName":"John","sn":"Doe","phone":"44600","details":"512"}]

Now use array.map()

const newArray = users.map(e => {
    return {...e, details: e.details==512 ? "active" : e.details};
});

If you only want to replace the text from details property then no need to convert the whole object into a string. You can simply iterate over the array using Array.map() method and then replace the details property value based on the regex .

Try this :

 const jsonObj = [{ "givenName": "helen", "sn": "brown", "phone": "44512", "details": "512" }, { "givenName": "John", "sn": "Doe", "phone": "44600", "details": "512" }]; const res = jsonObj.map(obj => { obj.details = obj.details.replace(/512/g, 'active'); return obj; }); console.log(res);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM