main.js (2160B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // VARIABLES // 22 23 /** 24 * Detects a JSON string. 25 * 26 * Regular expression: `/^\{[\s\S]*\}$|^\[[\s\S]*\]$/` 27 * 28 * - `^\{` 29 * 30 * - match a `{` literal which is the first character 31 * 32 * - `[\s\S]*` 33 * 34 * - match any whitespace and non-whitespace characters which occur `0` or more times 35 * 36 * - `\}$` 37 * 38 * - match a `}` literal which is the last character 39 * 40 * - `|` 41 * 42 * - alternatively 43 * 44 * - `^\[` 45 * 46 * - match a `[` literal which is the first character 47 * 48 * - `[\s\S]*` 49 * 50 * - match any whitespace and non-whitespace characters which occur `0` or more times 51 * 52 * - `\]$` 53 * 54 * - match a `]` literal which is the last character 55 * 56 * 57 * Example matching strings: 58 * 59 * - `'{}'` 60 * - `'[]'` 61 * - `'{adjlkfaj3743.,><\n\t\rdf}'` 62 * - `'[adjlkfaj3743.,><\n\t\rdf]'` 63 * - `'{"a":5}'` 64 * 65 * @constant 66 * @type {RegExp} 67 * @default /^\{[\s\S]*\}$|^\[[\s\S]*\]$/ 68 */ 69 var re = /^\{[\s\S]*\}$|^\[[\s\S]*\]$/; 70 71 72 // MAIN // 73 74 /** 75 * Tests if a value is a parseable JSON string. 76 * 77 * @param {*} value - value to test 78 * @returns {boolean} boolean indicating if a value is a parseable JSON string 79 * 80 * @example 81 * var v = isJSON( '{"a":5}' ); 82 * // returns true 83 * 84 * @example 85 * var v = isJSON( '{a":5}' ); 86 * // returns false 87 */ 88 function isJSON( value ) { 89 if ( typeof value !== 'string' ) { 90 return false; 91 } 92 if ( !re.test( value ) ) { 93 return false; 94 } 95 try { 96 JSON.parse( value ); 97 } catch ( err ) { // eslint-disable-line no-unused-vars 98 return false; 99 } 100 return true; 101 } 102 103 104 // EXPORTS // 105 106 module.exports = isJSON;