如何将所有json值转换为String而不进行迭代 [英] How to convert All json values to String without iteration
本文介绍了如何将所有json值转换为String而不进行迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有JSON,其中所有值都必须更改为字符串。值可以是数字,布尔值,未定义或null。
I have JSON in which all the values have to be changed to string. The values may be a number, boolean, undefined or null.
{
"obj1": [{
"n1": "n",
"n2": 1,
"n3": true
},
{
"n1": "n",
"n2": 1,
"n3": null
}]
}
预期结果是所有值都应格式化为字符串
。
The expected result is all the values should be formatted as a string
.
示例:
{
"obj1": [{
"n1": "n",
"n2": "1",
"n3": "true"
},
{
"n1": "n",
"n2": "1",
"n3": "null"
}]
}
通过迭代JSON对象,我们可以做到这一点,但有没有更简单的方法来做到这一点。
By iterating through the JSON object we can do this, but is there any simpler way to do this.
推荐答案
您可以 JSON.stringify
带有一个替换器函数并检查值是否为数字,然后取一个弦乐值,或者只取值。
You could take JSON.stringify
with a replacer function and check if the values is a number, then take a stringed value, or just the value.
var object = { obj1: [{ n1: "n", n2: 1, n3: true }, { n1: "n", n2: 1, n3: null }] },
json = JSON.stringify(object, (k, v) => v && typeof v === 'object' ? v : '' + v);
console.log(json);
console.log(JSON.parse(json));
这篇关于如何将所有json值转换为String而不进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文