UNPKG

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