0

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.

1
  • 1
    Well that format is called JSON, and the methods JSON.stringify and JSON.parse convert an object to a string and a string to an object respectively. As for changing the property, just do Response.Data.Serial = parseInt(Response.Data.Serial) Commented Nov 1, 2022 at 16:54

3 Answers 3

3

simply : ?

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


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

console.log(mydata)

Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

1

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.