UNPKG

ts-json-simple

Version:

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

89 lines (88 loc) 2.28 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const JSONArray_1 = __importDefault(require("./JSONArray")); class JSONObject { constructor(properties = {}) { this.properties = properties; } element(key, value) { this.properties[key] = value; return this; } elementIf(condition, key, value) { if (condition) { this.properties[key] = value; } return this; } elementMap(key, map) { this.properties[key] = new JSONObject(); for (const [value, key] of map) { this.properties[key].element(String(key), value); } return this; } accumulateAll(map) { for (const [value, key] of map) { this.element(String(key), value); } return this; } has(key) { return key in this.properties; } get(key) { return this.properties[key]; } remove(key) { if (key in this.properties) { delete this.properties[key]; } return this; } getString(key) { const value = this.properties[key]; if (typeof value === 'string') { return value; } return null; } getNumber(key) { const value = this.properties[key]; if (typeof value === 'number') { return value; } return undefined; } getBoolean(key) { const value = this.properties[key]; if (typeof value === 'boolean') { return value; } return undefined; } getJSONObject(key) { const value = this.properties[key]; if (value instanceof JSONObject) { return value; } return undefined; } getJSONArray(key) { const value = this.properties[key]; if (value instanceof JSONArray_1.default) { return value; } return undefined; } toJSON() { return this.properties; } get isEmpty() { return Object.keys(this.properties).length === 0; } } exports.default = JSONObject;