Test for JSON/JSONarray
Demonstartion of a function to test for valid JSON and JSON array
by fatmonk
HTML
<div style="border: solid grey 1px;padding: 5px">
<b>Set Up Test</b><hr />
<select id='testSelect' onChange="enableDisableTextArea()">
<option value='{ "a": 1 }'>Test 1: data = '{ "a": 1 }'</option>
<option value='[{ "b": 2 }]'>Test 2: data = '[{ "b": 2 }]'</option>
<option value='[{ 2 }]'>Test 3: data = '[{ 2 }]'</option>
<option value='2'>Test 4: data = '2'</option>
<option value=''>Test 5: date = ''</option>
<option value='null'>Test 6: data is not defined</option>
<option value='user'>User defined test (see below)</option>
</select>
<input type="button" value="Run Test" id="bRunTest" onClick="runTest()"><br />
<textarea disabled style="width: 90%" id="userTestData" placeholder="User test data"></textarea>
</div>
<div style="border: solid grey 1px;padding: 5px">
<b>Result</b><hr />
<textarea disabled style="width: 90%" id="resultArea" rows="4"></textarea>
</div>
JavaScript
// This is the implementation of the test for JSON function
// Note that expected results are listed below in the text of the original answer from StackOverflow
function testForJSON(data) {
var isValidJSON = data ? true : false
try { JSON.parse(data) } catch(e) { isValidJSON = false }
var isJSONarray = isValidJSON && JSON.parse(data).length ? true : false;
// Output result in result textarea
document.getElementById("resultArea").value = "";
document.getElementById("resultArea").value += "data isValidJSON: " + isValidJSON + "\n";
document.getElementById("resultArea").value += "data isJSONArray: " + isJSONarray + "\n";
document.getElementById("resultArea").value += "Test data : " + data + "\n";
}
// Function below are for interaction of this test page
function runTest() {
var sel = document.getElementById("testSelect");
if (sel.options[sel.selectedIndex].value == 'null') {
var data;
} else if (sel.options[sel.selectedIndex].value == 'user') {
var data = document.getElementById("userTestData").value;
} else {
var data = sel.options[sel.selectedIndex].value;
}
// alert("Test data = "+data);
testForJSON(data);
}
function enableDisableTextArea() {
var sel = document.getElementById("testSelect");
if (sel.options[sel.selectedIndex].value == 'user') {
document.getElementById("userTestData").disabled = false;
} else {
document.getElementById("userTestData").disabled = true;
}
}
// The following is the text from the original StackOverflow Answer by efkan
// http://stackoverflow.com/a/39236371/2211491
/*
// TEST 1
var data = '{ "a": 1 }'
// Avoiding 'null' trap! Null is confirmed as JSON.
var isValidJSON = data ? true : false
try { JSON.parse(data) } catch(e) { isValidJSON = false }
console.log("data isValidJSON: ", isValidJSON);
console.log("data isJSONArray: ", isValidJSON && JSON.parse(data).length ? true : false);
Console outputs:
data isValidJSON: true
data isJSONArray: false
// TEST 2
var data2 = '[{ "b": 2...