我的JSON字符串是:
{name:"MyNode", width:200, height:100}我想将其更改为:
{name:"MyNode", width:"200", height:"100"}这样所有整数值都会变成字符串
我的主要代码是:
{
"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
}
]
}我需要所有整数值都变成字符串
发布于 2011-09-12 22:45:41
这是一个JavaScript对象文字,而不是JSON。不管怎样..。
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"}如果您实际使用的是JSON,而不是对象,那么请在事前对字符串执行JSON.parse(),然后对对象执行JSON.stringify()操作。
发布于 2011-09-12 23:00:12
如果必须对JSON字符串进行操作:
json = json.replace (/:(\d+)([,\}])/g, ':"$1"$2');发布于 2019-09-04 14:31:38
我使用
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;
} 在我看来,大多数in都应该是字符串。如果您的api不能以字符串形式提供ids,此代码段将对其进行转换。
https://stackoverflow.com/questions/7389598
复制相似问题