나는 이것이 좋은 대답을 가진 아주 오래된 질문이라는 것을 알고 있습니다. 그러나 여전히 2 ¢를 추가 할 수있는 것 같습니다.
JSON 객체 자체가 아니라 JSON 형식의 문자열 (에서 케이스 인 것 같음)을 테스트하려고한다고 가정하면 var data부울을 반환하는 다음 함수를 사용할 수 있습니다 ( ' JSON ') :
function isJsonString( jsonString ) {
let printError = function(error, explicit) {
console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
}
try {
JSON.parse( jsonString );
return true;
} catch (e) {
return false;
}
}
위의 함수를 사용하는 몇 가지 예는 다음과 같습니다.
console.log('\n1 -----------------');
let j = "abc";
console.log( j, isJsonString(j) );
console.log('\n2 -----------------');
j = `{"abc": "def"}`;
console.log( j, isJsonString(j) );
console.log('\n3 -----------------');
j = '{"abc": "def}';
console.log( j, isJsonString(j) );
console.log('\n4 -----------------');
j = '{}';
console.log( j, isJsonString(j) );
console.log('\n5 -----------------');
j = '[{}]';
console.log( j, isJsonString(j) );
console.log('\n6 -----------------');
j = '[{},]';
console.log( j, isJsonString(j) );
console.log('\n7 -----------------');
j = '[{"a":1, "b": 2}, {"c":3}]';
console.log( j, isJsonString(j) );
위의 코드를 실행하면 다음과 같은 결과가 나타납니다.
1 -----------------
abc false
2 -----------------
{"abc": "def"} true
3 -----------------
{"abc": "def} false
4 -----------------
{} true
5 -----------------
[{}] true
6 -----------------
[{},] false
7 -----------------
[{"a":1, "b": 2}, {"c":3}] true
아래 스 니펫을 시도해보고 이것이 당신에게 맞는지 알려주십시오. :)
중요 :이 게시물에 제시된 함수는 https://airbrake.io/blog/javascript-error-handling/syntaxerror-json-parse-bad-parsing 에서 조정되었으며 여기에서 JSON.parse (에 대한 더 많은 흥미로운 세부 정보를 찾을 수 있습니다. ) 함수.
function isJsonString( jsonString ) {
let printError = function(error, explicit) {
console.log(`[${explicit ? 'EXPLICIT' : 'INEXPLICIT'}] ${error.name}: ${error.message}`);
}
try {
JSON.parse( jsonString );
return true;
} catch (e) {
return false;
}
}
console.log('\n1 -----------------');
let j = "abc";
console.log( j, isJsonString(j) );
console.log('\n2 -----------------');
j = `{"abc": "def"}`;
console.log( j, isJsonString(j) );
console.log('\n3 -----------------');
j = '{"abc": "def}';
console.log( j, isJsonString(j) );
console.log('\n4 -----------------');
j = '{}';
console.log( j, isJsonString(j) );
console.log('\n5 -----------------');
j = '[{}]';
console.log( j, isJsonString(j) );
console.log('\n6 -----------------');
j = '[{},]';
console.log( j, isJsonString(j) );
console.log('\n7 -----------------');
j = '[{"a":1, "b": 2}, {"c":3}]';
console.log( j, isJsonString(j) );