Skip to content

Instantly share code, notes, and snippets.

@mividtim
Last active November 7, 2018 13:09
Show Gist options
  • Save mividtim/97db63bda3484d9629b496df0f2ce200 to your computer and use it in GitHub Desktop.
Save mividtim/97db63bda3484d9629b496df0f2ce200 to your computer and use it in GitHub Desktop.
Flow type definition (libdef) for Json, and ToJson which drops non-serializable props
// @flow
// Flow type definition for Json (lower-case so as not to collide with JSON)
// ToJson function accepts any JS variable and sets any non-serializable
// vars or properties on objects to null
// The author has found this quite useful for logging complex objects safely
export type JsonPrimitive = null | string | number | boolean;
export type JsonObject = { [string]: Json };
export type JsonArray = Json[];
export type Json = JsonPrimitive | JsonObject | JsonArray;
export function isPrimitive(value: any): boolean {
return value === null || ['string', 'number', 'boolean'].includes(value);
}
export function ArrayToJson(array: any[]): JsonArray {
return array.reduce(
(json: JsonArray, value: any): JsonArray => {
return Array.isArray(json)
? [...json, ToJson(value)]
: [ToJson(value)];
},
);
}
export function ObjectToJson(object: Object): JsonObject {
return Object.keys(object).reduce(
(json: JsonObject, key: string): JsonObject => {
return typeof json === 'object'
&& !Array.isArray(json)
? { ...json, [key]: ToJson(object[key]) }
: { [key]: ToJson(object[key]) };
},
{},
);
}
export function ToJson(value: any): Json {
return isPrimitive(value) ? value
: Array.isArray(value) ? ArrayToJson(value)
: typeof value === 'object' ? ObjectToJson(value)
: null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment