Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JSON stringify's replacer function

I am trying to update few JSON values from string to numbers. I read about the "replacer" function from MDN and tried to make it work. However, there is no effect to the actual json output. Not sure what is going wrong here. Any help/suggestion here is much appreciated. Here’s something I tried:

const NUMBER_FIELDS = [
  'count',
  'age',
  'hours',
];

const payload = {
    "name":  "John Doe",
    "age": "35",
    "country": "Canada",
    "count": 4,
    "hours": "100"
}

function replacer(key, value) {
  NUMBER_FIELDS.forEach((field) => {
    if (key && key === field && typeof value === 'string') {
      return parseInt(value, 10);
    }
    return field;
  });

  return value;
 }

const postBody = JSON.stringify(payload, replacer);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You had the right idea, but the issue is you are not going to return from a forEach.

Just check if the key exists in the array and if it does return it as a number.

const NUMBER_FIELDS = [
  'count',
  'age',
  'hours',
];

const payload = {
    "name":  "John Doe",
    "age": "35",
    "country": "Canada",
    "count": 4,
    "hours": "100"
}

function replacer(key, value) {
  return NUMBER_FIELDS.includes(key) ? +value : value;
 }

const postBody = JSON.stringify(payload, replacer);
console.log(postBody);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading