Skip to content Skip to sidebar Skip to footer

How To Convert A JSON String Into A JavaScript Object Including Type Checking

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 id

Solution 1:

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;
});

Post a Comment for "How To Convert A JSON String Into A JavaScript Object Including Type Checking"