jsonify

A utility function to safely serialize and deserialize an object or array, handling `bigint` and `Date` values.
> jsonify<T extends object | object[]>(data: T | null): T | null
Parameters
  • data (T | null): The object or array to serialize and deserialize. If the value is `null`, the function will return `null`.
  • Returns: A new object or array with `bigint` values converted to numbers (if possible) and `Date` strings converted to `Date` objects. If an error occurs during serialization or deserialization, it returns `null`.

Example

import { jsonify } from "@explita/daily-toolset";

// Sample object containing different types of values
const data = {
  name: "John Doe",
  age: 30,
  birthdate: "1994-05-14T00:00:00Z",
  balance: BigInt("1000000000000"),
};

// Serializing and deserializing the data
const transformedData = jsonify(data);
console.log(transformedData);
// Output: { name: "John Doe", age: 30, birthdate: Date, balance: 1000000000000 }

const invalidData = jsonify(null);
console.log(invalidData); // null

Use Cases

  • Converting `bigint` to number, where applicable, for compatibility with JSON serialization.
  • Converting `Date` strings back to `Date` objects when deserializing JSON.
  • Safely handling the serialization and deserialization of objects or arrays containing special data types like `bigint` or `Date`.