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

应该是正确的

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

应该为假。

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


当前回答

下面是我的工作代码:

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

其他回答

在prototypeJS中,我们有方法isJSON。你可以试试。甚至json也可能有所帮助。

"something".isJSON();
// -> false
"\"something\"".isJSON();
// -> true
"{ foo: 42 }".isJSON();
// -> false
"{ \"foo\": 42 }".isJSON();
// -> true

如果你不想在任何地方执行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

我从开头的注释推断,用例描述的是响应是HTML还是JSON。在这种情况下,当您确实收到JSON时,您可能应该解析它并在代码中的某个位置处理无效JSON。除此之外,我想如果您的浏览器收到了JSON但无效的JSON,您会希望得到通知(用户也会通过代理收到一些有意义的错误消息)!

因此,为JSON执行完整的正则表达式是不必要的(根据我的经验,对于大多数用例来说,这是不必要的)。你可能会更好地使用下面的方法:

function (someString) {
  // test string is opened with curly brace or machine bracket
  if (someString.trim().search(/^(\[|\{){1}/) > -1) {
    try { // it is, so now let's see if its valid JSON
      var myJson = JSON.parse(someString);
      // yep, we're working with valid JSON
    } catch (e) {
      // nope, we got what we thought was JSON, it isn't; let's handle it.
    }
  } else {
    // nope, we're working with non-json, no need to parse it fully
  }
}

这应该节省你不得不异常处理有效的非json代码,同时照顾duff json。

对于喜欢. 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
});

保持简单

函数isValidJsonString(测试器) / /早期现有 If (/^\s*$|undefined/.test(tester) || !(/number|object|array|string|boolean/。测试(typeof测试仪))) { 返回错误; }; //通过try catch进行解析 返回true; };