README.md (2102B)
1 <!-- 2 3 @license Apache-2.0 4 5 Copyright (c) 2018 The Stdlib Authors. 6 7 Licensed under the Apache License, Version 2.0 (the "License"); 8 you may not use this file except in compliance with the License. 9 You may obtain a copy of the License at 10 11 http://www.apache.org/licenses/LICENSE-2.0 12 13 Unless required by applicable law or agreed to in writing, software 14 distributed under the License is distributed on an "AS IS" BASIS, 15 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 See the License for the specific language governing permissions and 17 limitations under the License. 18 19 --> 20 21 # isJSON 22 23 > Test if a value is a parseable JSON string. 24 25 <section class="usage"> 26 27 ## Usage 28 29 ```javascript 30 var isJSON = require( '@stdlib/assert/is-json' ); 31 ``` 32 33 #### isJSON( value ) 34 35 Tests if a `value` is a parseable JSON `string`. 36 37 ```javascript 38 var value = '{"a":5}'; 39 40 var bool = isJSON( value ); 41 // returns true 42 ``` 43 44 </section> 45 46 <!-- /.usage --> 47 48 <section class="notes"> 49 50 ## Notes 51 52 - The implementation validates that the input `value` is a `string` literal. For all other inputs, the method returns `false`. 53 54 - The implementation validates that a `string` begins with either `[` or `{` and ends with a corresponding `]` or `}`, respectively. Hence, the method will return `false` for the following `strings`, despite `JSON.parse` accepting their input: 55 56 - `'<number>'` (e.g., `'5'`) 57 - `'<boolean>'` (e.g., `'true'`) 58 - `'null'` 59 60 - The implementation wraps `JSON.parse` inside a `try/catch`. Hence, this function cannot be optimized by the compiler during runtime. Nevertheless, using this function is better than embedding a `try/catch` within a larger `function` which could be optimized in the absence of a `try/catch`. 61 62 </section> 63 64 <!-- /.notes --> 65 66 <section class="examples"> 67 68 ## Examples 69 70 <!-- eslint no-undef: "error" --> 71 72 ```javascript 73 var isJSON = require( '@stdlib/assert/is-json' ); 74 75 var bool = isJSON( '{"a":5}' ); 76 // returns true 77 78 bool = isJSON( '{a":5}' ); 79 // returns false 80 ``` 81 82 </section> 83 84 <!-- /.examples --> 85 86 <section class="links"> 87 88 </section> 89 90 <!-- /.links -->