Lenka
Lenka

Reputation: 75

Convert a particular JSON element to integer using javascript

I am bit new to javascript and I want to change a particular JSON element to string without changing the whole JSON.

Input:

   {
       "Response" : {
          "Data" : {
             "Type" : "Set",
             "Serial" : "75798"
          }
       }
    }

The output I wanted is:

{
   "Response" : {
      "Data" : {
         "Type" : "Set",
         "Serial" : 75798
      }
   }
}

Got to know about parseInt function but not sure how to write the full code where I get the output as above after it processed by the javascript.

Upvotes: 0

Views: 110

Answers (3)

Jim
Jim

Reputation: 597

You can try converting to/from a regular object:

let json = `{
  "Response": {
    "Data": {
      "Serial":  "75798"
    }
  }
}`

let obj = JSON.parse(json);
obj.Response.Data.Serial = parseInt(obj.Response.Data.Serial);

let newJson = JSON.stringify(obj);

console.log(newJson);

Upvotes: 2

Carsten Massmann
Carsten Massmann

Reputation: 28196

In case you are looking for a way to convert all numeric strings in an object structure to numbers you could try the following recursive function toNum():

const data={"arr":[{"a":"33.546","b":"bcd"},"3354","11/12/2022"],"Response":{"Data":{"Type":"Set","Serial":"75798"}, "xtra":"4711","xtra2":"34x56"}};
 
function toNum(o,i,arr){
 if (typeof o=="string" && !isNaN(o)) {
  o = +o; 
  if (arr) arr[i] = o; // o is an array element => arr[i] !!
 }
 else {
  for (p in o){
   let typ=typeof o[p]
   if (typ=="object") 
     if(Array.isArray(o[p])) o[p].forEach(toNum);
     else toNum(o[p]);
   if (typ=="string" && !isNaN(o[p])) o[p] = +o[p];
  }
 }
 return o
}

// toNum() works on "anything" ...
console.log(toNum(data));    // a mixed object
console.log(toNum("12345")); // a single string
console.log(toNum(["abc",new Date(),"-6.542","def"])); // or an array (with a Date() object in it)

Upvotes: 1

Mister Jojo
Mister Jojo

Reputation: 22275

simply : ?

const mydata =   {
       "Response" : {
          "Data" : {
             "Type" : "Set",
             "Serial" : "75798"
          }
       }
    }


mydata.Response.Data.Serial = Number(mydata.Response.Data.Serial)

console.log(mydata)

Upvotes: 3

Related Questions