1

I would like to replace a json string from:

[{"id":151,"name":"me"}, {"id":4567432,"name":"you"}]

to:

[{"id":"151","name":"me"}, {"id":"4567432","name":"you"}]

As you can see, I just want to add parentheses to the id's value(some number).

I tried:

json = json.replaceAll("\"id\",([0-9]+)", "\"id\",\"$1\"");

but it doesn't work. How can I do it?

1
  • "...I just want to add parentheses..." They are double quotes, not parentheses. Commented Aug 1, 2021 at 17:58

2 Answers 2

1

You are using commas as key-value separator, but in the sample string, you have a colon.

You can fix the replaceAll method if you use

replaceAll("(\"id\":)([0-9]+)", "$1\"$2\"")

See the online regex demo.

Details:

  • (\"id\":) - Group 1 ($1): "id": string
  • ([0-9]+) - Group 2 ($2): one or more digits
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, perfect! King! :)
0

with js code

// #js code

const data = [{"id":151,"name":"me"}, {"id":4567432,"name":"you"}];

function solve1(data) {
  // solution 1
  // with stringify data
  const getMatches = data.match(/\"id\"\:\d+\,/gi);
  getMatches?.forEach((theMatch)=>{
    const getNumbers = theMatch.match(/\d+/gi).join("");
    const newMatch = theMatch.replace(getNumbers,`"${getNumbers}"`);
    data = data.replace(theMatch,newMatch)
  })
  return data;
}
function solve2(data) {

  // solution 2
  // with json data
  return data.map((item)=>{
    item.id = item.id.toString(); 
    return item;
  })
}
console.log(solve1(JSON.stringify(data)));
console.log(solve2(data))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.