[javascript] AJAX : 문자열이 JSON인지 확인합니까?

내 JavaScript는 때때로 다음 줄에서 충돌합니다.

var json = eval('(' + this.responseText + ')');

의 인수 eval()가 JSON이 아닌 경우 충돌이 발생합니다 . 이 호출을하기 전에 문자열이 JSON인지 확인하는 방법이 있습니까?

프레임 워크를 사용하고 싶지 않습니다. 사용하여이 작업을 수행 할 수있는 방법이 eval()있습니까? (좋은 이유가 있습니다. 약속합니다.)



답변

json.org 의 JSON 파서 를 포함하는 경우 parse () 함수를 사용하고 다음과 같이 try / catch로 래핑 할 수 있습니다.

try
{
   var json = JSON.parse(this.responseText);
}
catch(e)
{
   alert('invalid json');
}

그런 것이 아마도 당신이 원하는 것을 할 것입니다.


답변

그녀는 jQuery 대안입니다 …

try
{
  var jsonObject = jQuery.parseJSON(yourJsonString);
}
catch(e)
{
  // handle error 
}


답변

JSON 과 직렬화를 위해 javascript JSON 라이브러리 를 사용하는 것이 좋습니다 . 절대적으로 확신eval() 하지 않는 한 절대 사용해서는 안되는 보안 위험입니다.입력 내용이 완전하고 안전하다는 이 .

JSON 라이브러리가 parse()있는 상태에서 try / catch-block에 해당 하는 호출을 래핑하여 JSON이 아닌 입력을 처리합니다.

try
{
  var jsonObject = JSON.parse(yourJsonString);
}
catch(e)
{
  // handle error 
}


답변

도움이 될 수 있습니다.이 코드를 사용하면 데이터를 직접 가져올 수 있습니다.

<!DOCTYPE html>
<html>
<body>

<h3>Open console, please, to view result!</h3>
<p id="demo"></p>

<script>
var tryJSON = function (test) {
	try {
	    JSON.parse(test);
	}
	catch(err) {
    	// maybe you need to escape this… (or not)
	    test = '"'+test.replace(/\\?"/g,'\\"')+'"';
	}
	eval('test = '+test);
	console.debug('Try json:', test);
};

// test with string…
var test = 'bonjour "mister"';
tryJSON(test);
// test with JSON…
var test = '{"fr-FR": "<p>Ceci est un texte en français !</p>","en-GB": "<p>And here, a text in english!</p>","nl-NL": "","es-ES": ""}';
tryJSON(test);
</script>

</body>
</html>


답변

try-catch접근 방식 에 따른 문제 JSON.parse('123') = 123는 예외가 발생하지 않는다는 것입니다. 따라서 외에도 try-catch다음과 같이 유형을 확인해야합니다.

function isJsonStr(str) {
    var parsedStr = str;
    try {
        parsedStr = JSON.parse(str);
    } catch (e) {
        return false;
    }
    return typeof parsedStr == 'object'
}


답변

응답이 무엇인지 확인할 수없는 이유는 무엇입니까? 더 효율적입니다.

var result;

if (response.headers['Content-Type'] === 'application/json')
    result = JSON.parse(this.responseText);
else
    result = this.responseText;

screen1


답변

JavaScript 유형을 확인하는 작은 라이브러리가 있습니다. is.js

is.json({foo: 'bar'});
=> true

// functions are returning as false
is.json(toString);
=> false

is.not.json([]);
=> true

is.all.json({}, 1);
=> false

is.any.json({}, 2);
=> true

// 'all' and 'any' interfaces can also take array parameter
is.all.json([{}, {foo: 'bar'}]);
=> true

사실 is.js 는 이것보다 훨씬 더 많은 것을 언급합니다.

var obj = document.createElement('div');
is.domNode(obj);
=> true

is.error(new Error());
=> true

is.function(toString);
=> true

is.chrome();
=> true if current browser is chrome