util-ex
Version:
Browser-friendly enhanced util fully compatible with standard node.js
56 lines (55 loc) • 1.57 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
exports.isJson = isJson;
var _string = _interopRequireDefault(require("../type/string.js"));
var _float = _interopRequireDefault(require("./float.js"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
/**
* Checks if a string is a valid JSON string.
*
* @param {string} v - The string to be checked.
* @param {boolean=} almost - If true, only checks if the string is almost JSON-like. Defaults to false.
* @returns {boolean} - Returns true if the string is valid JSON, false otherwise.
*
* @example
* isJson('{"name": "John", "age": 30}'); // true
* isJson('[1, 2, 3]'); // true
* isJson('{"name": "John", "age": 30'); // false
* isJson('This is not a JSON string.'); // false
*/
function isJson(v, almost) {
let lastIndex, result;
result = (0, _string.default)(v) && (v = v.trim()) !== '';
if (result) {
lastIndex = v.length - 1;
if (v[0] === '"') {
// or v[0] is "'"
result = v[lastIndex] === v[0];
if (result) {
return result;
}
} else if (v[0] === '{') {
result = v[lastIndex] === '}';
} else if (v[0] === '[') {
result = v[lastIndex] === ']';
} else {
result = (0, _float.default)(v);
if (result) {
return result;
}
}
if (result && !almost) {
try {
JSON.parse(v);
} catch (error) {
result = false;
}
}
}
return result;
}
;
var _default = exports.default = isJson;