My JSON string is:
{name:\"MyNode\", width:200, height:100}
I want to change it to:
{name:\"MyNode\", width:\"200\", height
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');
I use
const stringifyNumbers = obj => {
const result = {};
Object.entries(obj).map(entry => {
const type = typeof entry[1];
if (Array.isArray(entry[1])) {
result[entry[0]] = entry[1].map(entry => stringifyNumbers(entry));
} else if (type === 'object' && !!entry[1]) {
result[entry[0]] = stringifyNumbers(entry[1]);
} else if (entry[1] === null) {
result[entry[0]] = null;
} else if (type === 'number') {
result[entry[0]] = String(entry[1]);
} else {
result[entry[0]] = entry[1];
}
});
return result;
}
most ids should be strings in my opinion. If your api cannot provide ids as strings this snippet will convert them.