To properly extract information from a JSON string, it is recommended to use JSON.parse along with a reviver function:
var jsonString = '[{"name":"eric","age":"24"},{"name":"goulding","age":"23"}]';
// The reviver function checks if the value can be converted to a number
// If so, it returns the number; otherwise, it returns the original value
var reviver = function (key, value) {
var number = Number(value);
return number === number ? number : value;
};
// By providing the reviver function as a parameter,
// each key-value pair will be processed to determine the final value
var data = JSON.parse(jsonString, reviver);
When the reviver function is called with reviver("name", "eric")
, it returns "eric"
since strings cannot be converted to numbers. However, calling it with reviver("age", "24")
will result in returning the number 24
.
It's important to note that although
[{"name":"eric","age":"24"},{"name":"goulding","age":"23"}]
is an array and not directly JSON, the string version
'[{"name":"eric","age":"24"},{"name":"goulding","age":"23"}]'
represents valid JSON formatted data.