isJsonString('{ "Id": 1, "Name": "Coke" }')

应该是正确的

isJsonString('foo')
isJsonString('<div>foo</div>')

应该为假。

我正在寻找一种不使用try/catch的解决方案,因为我将调试器设置为“在所有错误上中断”,这导致它在无效的JSON字符串上中断。


当前回答

我想我知道你为什么不想这么做。但也许试着去抓!;o)我突然想到:

var json_verify = function(s){ try { JSON.parse(s); return true; } catch (e) { return false; }};

所以你也可以对JSON对象进行脏剪辑,比如:

JSON.verify = function(s){ try { JSON.parse(s); return true; } catch (e) { return false; }};

由于这是尽可能封装的,它可能不会在错误时中断。

其他回答

对于喜欢. net惯例中的“try”函数,它返回一个布尔值并处理一个包含结果的byref参数。如果不需要out参数,可以省略它,只使用返回值。

StringTests.js

  var obj1 = {};
  var bool1 = '{"h":"happy"}'.tryParse(obj1); // false
  var obj2 = {};
  var bool2 = '2114509 GOODLUCKBUDDY 315852'.tryParse(obj2);  // false

  var obj3 = {};
  if('{"house_number":"1","road":"Mauchly","city":"Irvine","county":"Orange County","state":"California","postcode":"92618","country":"United States of America","country_code":"us"}'.tryParse(obj3))
    console.log(obj3);

StringUtils.js

String.prototype.tryParse = function(jsonObject) {
  jsonObject = jsonObject || {};
  try {
    if(!/^[\[{]/.test(this) || !/[}\]]$/.test(this)) // begin / end with [] or {}
      return false; // avoid error handling for strings that obviously aren't json
    var json = JSON.parse(this);
    if(typeof json === 'object'){
      jsonObject.merge(json);
      return true;
    }
  } catch (e) {
    return false;
  }
}

ObjectUtils.js

Object.defineProperty(Object.prototype, 'merge', {
  value: function(mergeObj){
    for (var propertyName in mergeObj) {
      if (mergeObj.hasOwnProperty(propertyName)) {
        this[propertyName] = mergeObj[propertyName];
      }      
    }
    return this;
  },
  enumerable: false, // this is actually the default
});

如果你有疑问,值是或不是json

  function isStringified(jsonValue) { // use this function to check
   try {
    console.log("need to parse");
    return JSON.parse(jsonValue);
   } catch (err) {
    console.log("not need to parse");

     return jsonValue; 
    }
  }

然后

  const json = isStringified(stringValue);

  if (typeof json == "object") {
      console.log("string is a valid json")
    }else{
      console.log("string is not a valid json")
    }

如果你不想在任何地方执行try/catch,寻找一个单一的行程序,并且不介意使用异步函数:

const isJsonString = async str => ( await ((async v => JSON.parse(v))(str)).then(_ => true).catch(_ => false) );

await isJsonString('{ "Id": 1, "Name": "Coke" }'); // true
await isJsonString('foo'); // false
await isJsonString('<div>foo</div>'); // false

你可以使用javascript的eval()函数来验证它是否有效。

e.g.

var jsonString = '{ "Id": 1, "Name": "Coke" }';
var json;

try {
  json = eval(jsonString);
} catch (exception) {
  //It's advisable to always catch an exception since eval() is a javascript executor...
  json = null;
}

if (json) {
  //this is json
}

或者,您也可以使用JSON。解析函数来自json.org:

try {
  json = JSON.parse(jsonString);
} catch (exception) {
  json = null;
}

if (json) {
  //this is json
}

希望这能有所帮助。

警告:如果有人添加了恶意的JS代码,eval()是危险的,因为它会执行它。确保JSON字符串是可信的,即你从一个可信的来源。

对于我的第一个解决方案,建议这样做。

 try {
      json = eval("{" + jsonString + "}");
    } catch (exception) {
      //It's advisable to always catch an exception since eval() is a javascript executor...
      json = null;
    }

保证json的一致性。如果jsonString不是纯JSON, eval将抛出异常。

if(resp) {
    try {
        resp = $.parseJSON(resp);
        console.log(resp);
    } catch(e) {
        alert(e);
    }
}

希望这也适用于你