Reputation: 291
I am getting response from server in the following format:
[{"key":"Idle Time","values":[{"x":"SADSA","y":"4.0"},{"x":"FDDG","y":"6.0"},{"x":"FF","y":"4.15"}]},{"key":"Operational Time","values":[{"x":"SADSA","y":"20.0"},{"x":"FDDG","y":"18.0"},{"x":"FF","y":"19.45"}]}]
I need to convert this to json format so I used JSON.parse
. This is what I got:
[{key:"Idle Time",values:[{x:"SADSA",y:"4.0"},{x:"FDDG",y:"6.0"},{x:"FF",y:"4.15"}]},{key:"Operational Time",values:[{x:"SADSA",y:"20.0"},{x:"FDDG",y:"18.0"},{x:"FF",y:"19.45"}]}]
But I want the following format:
[{key:"Idle Time",values:[{x:"SADSA",y:4.0},{x:"FDDG",y:6.0},{x:"FF",y:4.15}]},{key:"Operational Time",values:[{x:"SADSA",y:20.0},{x:"FDDG",y:18.0},{x:"FF",y:19.45}]}]
How can I get it?
Upvotes: 0
Views: 82
Reputation:
function convertToNo(a){
for (var i in a){
if (!isNaN(a[i])) a[i] = parseFloat(a[i]);
if (a[i].isArray()) return convertToNo(a[i]);
}
}
var newObj = convertToNo(oldObj);
This loops through the array and change all strings to numbers.
Upvotes: 1
Reputation: 386610
You could a reviver
function of JSON.parse
and convert numerical values to numbers.
Using the reviver parameter
If a
reviver
is specified, the value computed by parsing is transformed before being returned. Specifically, the computed value and all its properties (beginning with the most nested properties and proceeding to the original value itself) are individually run through thereviver
. Then it is called, with the object containing the property being processed asthis
, and with the property name as a string, and the property value as arguments. If thereviver
function returnsundefined
(or returns no value, for example, if execution falls off the end of the function), the property is deleted from the object. Otherwise, the property is redefined to be the return value.If the
reviver
only transforms some values and not others, be certain to return all untransformed values as-is, otherwise they will be deleted from the resulting object.
var json = '[{"key":"Idle Time","values":[{"x":"SADSA","y":"4.0"},{"x":"FDDG","y":"6.0"},{"x":"FF","y":"4.15"}]},{"key":"Operational Time","values":[{"x":"SADSA","y":"20.0"},{"x":"FDDG","y":"18.0"},{"x":"FF","y":"19.45"}]}]',
data = JSON.parse(json, (key, value) => !isNaN(value) ? +value : value);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 2
Reputation: 30739
The following code can also work for you:
var strJson = '[{"key":"Idle Time","values":[{"x":"SADSA","y":"4.0"},{"x":"FDDG","y":"6.0"},{"x":"FF","y":"4.15"}]},{"key":"Operational Time","values":[{"x":"SADSA","y":"20.0"},{"x":"FDDG","y":"18.0"},{"x":"FF","y":"19.45"}]}]';
var parsedJSON = JSON.parse(strJson);
var res = [];
parsedJSON.forEach((obj) => {
obj.values.forEach((innerObj) => {
innerObj.y = parseFloat(innerObj.y);
});
res.push(obj);
});
console.log(res);
Upvotes: 1