如果值的类型为数字,我想从json字符串中删除双引号。
示例输入字符串
"font": {
"style": "normal",
"weight": "normal",
"decoration": "none",
"size": "15",
"color": "#000000"
}
预期输出字符串
"font": {
"style": "normal",
"weight": "normal",
"decoration": "none",
"size": 15,
"color": "#000000"
}
怎么做?
答案 0 :(得分:0)
您可以遍历对象中的每个字段,检查其值是否为数字,如果是,请将其替换为:)
function doIt (myThingee) {
var keys = Object.keys(myThingee);
var value;
for (key in keys) {
value = parseInt(myThingee[key], 10);
if (!isNaN(value)) {
myThingee[key] = value;
}
}
}
答案 1 :(得分:0)
您可以尝试以下代码:
var obj = {
"style": "normal",
"weight": "normal",
"decoration": "111",
"size": "15",
"color": "#000000"
};
var newObj = {};
for (var key in obj) {
if (/^\d+$/.test(obj[key])) { //test for number Or use /[-+]?[0-9]*\.?[0-9]+/ for all kind of real numbers
newObj[key] = +obj[key];
} else {
newObj[key] = obj[key];
}
}
console.log(JSON.stringify(newObj))
newObj
将包含生成的对象。
答案 2 :(得分:0)
使用Number.isNaN
进行检查,并尝试使用+
运算符将其强制转换为数字。如果返回true,则什么也不做。如果为假,则将参数的值更改为强制转换数字。
var arr=[{"a":"b","c":"521"}];
arr.forEach(val => {
for(let key in val) Number.isNaN(+val[key]) || (val[key] = +val[key])
});
console.log(arr);