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
.
Example:
{
"obj1": [{
"n1": "n",
"n2": "1",
"n3": "true"
},
{
"n1": "n",
"n2": "1",
"n3": "null"
}]
}
By iterating through the JSON object we can do this, but is there any simpler way to do this.
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
.
Example:
{
"obj1": [{
"n1": "n",
"n2": "1",
"n3": "true"
},
{
"n1": "n",
"n2": "1",
"n3": "null"
}]
}
By iterating through the JSON object we can do this, but is there any simpler way to do this.
Share Improve this question edited Dec 8, 2018 at 20:12 Studio KonKon 7906 silver badges15 bronze badges asked Dec 8, 2018 at 19:16 ashokashok 1,2683 gold badges27 silver badges71 bronze badges 3- 3 What do you mean with "without iteration"? Some iteration is needed, hidden or explicit – Christian Vincenzo Traina Commented Dec 8, 2018 at 19:19
- You say you have JSON, so we are talking about one big string, right? – trincot Commented Dec 8, 2018 at 19:19
- I know behind it needs iteration but any simpler way which it works behind – ashok Commented Dec 8, 2018 at 19:28
3 Answers
Reset to default 14You 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));
You could do it with Json.stringify() method
for example:
var object = { obj1: [{ n1: "n", n2: 1, n3: true }, { n1: "n", n2: 1, n3: null }] };
and to see the result, use Json.stringify()
console.log(JSON.stringify(object, (key, value) => value ? value.toString() : value));
const obj = {
"obj1": [{
"n1": "n",
"n2": 1,
"n3": true
}, {
"n1": "n",
"n2": 1,
"n3": null
}]
};
const text = JSON.stringify(obj)
const newObj = text.replace(/:([^"[{][0-9A-Za-z]*)([,\]\}]?)/g, ':\"$1\"$2')
console.log(newObj);
/*
{"obj1":[{"n1":"n","n2":"1","n3":"true"},{"n1":"n","n2":"1","n3":"null"}]}
*/
// Em, let's format it
console.log(JSON.stringify(JSON.parse(newObj), null, 2));
/*
{
"obj1": [
{
"n1": "n",
"n2": "1",
"n3": "true"
},
{
"n1": "n",
"n2": "1",
"n3": "null"
}
]
}
*/