UNPKG

ts-json-simple

Version:

TypeScript package inspired by Java's JSONObject, providing a chainable API for JSON manipulation.

116 lines (85 loc) 2.27 kB
import type IJSONObject from "./IJSONObject"; import JSONArray from "./JSONArray"; import type {JSONValue} from "./JSONValue"; export default class JSONObject { constructor( private readonly properties: IJSONObject = {} ) { } public element(key: string, value: JSONValue): this { this.properties[key] = value; return this; } public elementIf(condition: boolean, key: string, value: JSONValue): this { if (condition) { this.properties[key] = value; } return this; } public elementMap(key: string, map: Map<any, any>): this { this.properties[key] = new JSONObject(); for (const [value, key] of map) { this.properties[key].element(String(key), value); } return this; } public accumulateAll(map: Map<any, any>): this { for (const [value, key] of map) { this.element(String(key), value); } return this; } public has(key: string): boolean { return key in this.properties; } public get(key: string): JSONValue { return this.properties[key]; } public remove(key: string) { if (key in this.properties) { delete this.properties[key]; } return this; } public getString(key: string): string | null { const value = this.properties[key]; if (typeof value === 'string') { return value; } return null; } public getNumber(key: string): number | undefined { const value = this.properties[key]; if (typeof value === 'number') { return value; } return undefined; } public getBoolean(key: string): boolean | undefined { const value = this.properties[key]; if (typeof value === 'boolean') { return value; } return undefined; } public getJSONObject(key: string): JSONObject | undefined { const value: any = this.properties[key]; if (value instanceof JSONObject) { return value; } return undefined; } public getJSONArray(key: string): JSONArray | undefined { const value: any = this.properties[key]; if (value instanceof JSONArray) { return value; } return undefined; } public toJSON(): IJSONObject { return this.properties; } public get isEmpty(): boolean { return Object.keys(this.properties).length === 0; } }