My JSON string is:
{name:"MyNode", width:200, height:100}
I want to change it to:
{name:"MyNode", width:"200", height:"100"}
so that all integer values become strings
My main code is:
{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address":
{
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"xy": 10021
},
"IDNumber":
[
{
"type": "home",
"number": 1234
},
{
"type": "fax",
"number": 4567
}
]
}
I need all integer values become strings
Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.
Valid Data Types In JSON, values must be one of the following data types: a string. a number. an object (JSON object)
Users can also Convert JSON File to Text by uploading the file. Download converted file with txt extension. JSON to Text Online works well on Windows, MAC, Linux, Chrome, Firefox, Edge, and Safari.
integer. The integer type is used for integral numbers. JSON does not have distinct types for integers and floating-point values.
That's a JavaScript object literal, not JSON. Anyway...
var obj = {name:"MyNode", width:200, height:100};
for (var k in obj)
{
if (obj.hasOwnProperty(k))
{
obj[k] = String(obj[k]);
}
}
// obj = {name:"MyNode", width: "200", height: "100"}
If you're actually working with JSON, not an object, JSON.parse()
the string beforehand, and JSON.stringify()
the object afterward.
If you must operate on the JSON string :
json = json.replace (/:(\d+)([,\}])/g, ':"$1"$2');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With