UNPKG

969 BJavaScriptView Raw
1import { stringify } from '../stringify.js';
2/**
3 * @name isJsonObject
4 * @summary Tests for a valid JSON `object`.
5 * @description
6 * Checks to see if the input value is a valid JSON object.
7 * It returns false if the input is JSON parsable, but not an Javascript object.
8 * @example
9 * <BR>
10 *
11 * ```javascript
12 * import { isJsonObject } from '@polkadot/util';
13 *
14 * isJsonObject({}); // => true
15 * isJsonObject({
16 * "Test": "1234",
17 * "NestedTest": {
18 * "Test": "5678"
19 * }
20 * }); // => true
21 * isJsonObject(1234); // JSON parsable, but not an object => false
22 * isJsonObject(null); // JSON parsable, but not an object => false
23 * isJsonObject('not an object'); // => false
24 * ```
25 */
26export function isJsonObject(value) {
27 const str = typeof value !== 'string'
28 ? stringify(value)
29 : value;
30 try {
31 const obj = JSON.parse(str);
32 return typeof obj === 'object' && obj !== null;
33 }
34 catch {
35 return false;
36 }
37}