如何判断正在使用哪个JSON对象(Crockford或其他)

How to tell which JSON object is being used (Crockford's or another)?

本文关键字:对象 JSON Crockford 其他 何判断 判断      更新时间:2023-09-26

我正在使用Crockford的json2.js。当我想串起来时,我确实JSON.stringify()...效果很好。

但是,看过代码的人知道它遵循现有的 JSON 对象和属性。我怀疑我遇到的某个问题可能是由于这种尊重。

是否有 JSON 对象的属性,我可以检查浏览器是否正在使用 Crockford 的对象或其他对象?能够做这样的事情会很好alert(JSON.version());

您可以决定像这样使用一个:

<script>window.JSON || document.write('<script src="js/json2.js"><'/script>')</script>

如果存在,这将首先检查window.JSON(浏览器支持),否则使用导入 crockford 的 json2.js。

更新

var whichJSON = null;
if (! window.JSON) {
  document.write('<script src="js/json2.js"><'/script>');
  whichJSON = 'Crockford Version';
}
else {
  whichJSON = 'Browser Native Version';
}
alert(whichJSON);

在加载 Crockford 的脚本之前,您可以像他一样检查全局 JSON 对象:

<script>
    var JSON,
        nativeJSON = true;
    if (!JSON) {
        var nativeJSON = false;
        document.write('<script src="js/json2.js"><'/script>');
    }
    if (!nativeJSON) {
        // All JSON objects are using Crockford's implementation
    } else {
        // All JSON objects from here on out are NOT using Crockford's implementation
    }
</script>