UNPKG

@naturalcycles/js-lib

Version:

Standard library for universal (browser + Node.js) javascript

52 lines (51 loc) 1.58 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports._jsonParseIfPossible = _jsonParseIfPossible; exports._jsonParseOrUndefined = _jsonParseOrUndefined; exports._jsonParse = _jsonParse; const error_util_1 = require("../error/error.util"); // const possibleJsonStartTokens = ['{', '[', '"'] const DETECT_JSON = /^\s*[{["\-\d]/; /** * Attempts to parse object as JSON. * Returns original object if JSON parse failed (silently). */ function _jsonParseIfPossible(obj, reviver) { // Optimization: only try to parse if it looks like JSON: starts with a json possible character if (typeof obj === 'string' && obj && DETECT_JSON.test(obj)) { try { return JSON.parse(obj, reviver); } catch { } } return obj; } /** * Convenience function that does JSON.parse, but doesn't throw on error, * instead - safely returns `undefined`. */ function _jsonParseOrUndefined(obj, reviver) { // Optimization: only try to parse if it looks like JSON: starts with a json possible character if (typeof obj === 'string' && obj && DETECT_JSON.test(obj)) { try { return JSON.parse(obj, reviver); } catch { } } } /** * Same as JSON.parse, but throws JsonParseError: * * 1. It's message includes a piece of source text (truncated) * 2. It's data.text contains full source text */ function _jsonParse(s, reviver) { try { return JSON.parse(s, reviver); } catch { throw new error_util_1.JsonParseError({ text: s, }); } }