Reputation: 13
For a Javascript project I have an json string converted into a Javascript object. But the type of all my values is 'string' becaus of the JSON parsing.
Is there any solution to identify the types and let a script convert them into the correct javascript type?
for example
//Javascript object for the json decoded string
var jsonObj = { id: "foo", count: "1" };
All the values are of type 'string' but I want count to be seen as a number. Is there a parser to set the correct type or does it need to be done manual in JS?
Upvotes: 0
Views: 2010
Reputation: 120486
You can use a reviver with JSON.parse
.
json2.js
describes the reviver thus
JSON.parse(text, reviver)
The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted.
So to convert count to a number you might do
JSON.parse(myJsonString, function (key, value) {
return key === "count" ? +value : value;
});
so
JSON.stringify(JSON.parse('{ "id": "foo", "count": "3" }', function (key, value) {
return key === "count" ? +value : value;
}));
produces
{"id":"foo","count":3}
EDIT
To handle dates as well, you can
JSON.parse(myJsonString, function (key, value) {
// Don't muck with null, objects or arrays.
if ("object" === typeof value) { return value; }
if (key === "count") { return +value; }
// Unpack keys like "expirationDate" whose value is represented as millis since epoch.
if (/date$/i.test(key)) { return new Date(+value); }
// Any other rules can go here.
return value;
});
Upvotes: 1