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

应该是正确的

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

应该为假。

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


当前回答

如果你有疑问,值是或不是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

使用JSON.parse这样的JSON解析器:

function isJsonString(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

我知道我问这个问题已经晚了3年,但我还是想插话。

虽然Gumbo的解决方案工作得很好,但它不能处理一些没有引发JSON异常的情况。解析({非JSON})

我也更喜欢同时返回解析后的JSON,这样调用代码就不必再次调用JSON.parse(jsonString)。

这似乎很适合我的需求:

/**
 * If you don't care about primitives and only objects then this function
 * is for you, otherwise look elsewhere.
 * This function will return `false` for any valid json primitive.
 * EG, 'true' -> false
 *     '123' -> false
 *     'null' -> false
 *     '"I'm a string"' -> false
 */
function tryParseJSONObject (jsonString){
    try {
        var o = JSON.parse(jsonString);

        // Handle non-exception-throwing cases:
        // Neither JSON.parse(false) or JSON.parse(1234) throw errors, hence the type-checking,
        // but... JSON.parse(null) returns null, and typeof null === "object", 
        // so we must check for that, too. Thankfully, null is falsey, so this suffices:
        if (o && typeof o === "object") {
            return o;
        }
    }
    catch (e) { }

    return false;
};
// vanillaJS
function isJSON(str) {
    try {
        return (JSON.parse(str) && !!str);
    } catch (e) {
        return false;
    }
}

用法:isJSON({})将为假,isJSON('{}')将为真。

检查某物是否是数组或对象(解析JSON):

// vanillaJS
function isAO(val) {
    return val instanceof Array || val instanceof Object ? true : false;
}

// ES2015
var isAO = (val) => val instanceof Array || val instanceof Object ? true : false;

用法:isAO({})为真,isAO('{}')为假。

我使用了一个非常简单的方法来检查字符串是否为有效的JSON。

function testJSON(text){
    if (typeof text!=="string"){
        return false;
    }
    try{
        var json = JSON.parse(text);
        return (typeof json === 'object');
    }
    catch (error){
        return false;
    }
}

返回一个有效的JSON字符串:

var input='["foo","bar",{"foo":"bar"}]';
testJSON(input); // returns true;

返回一个简单的字符串;

var input='This is not a JSON string.';
testJSON(input); // returns false;

返回一个对象:

var input={};
testJSON(input); // returns false;

输入为空的结果:

var input=null;
testJSON(input); // returns false;

最后一个返回false,因为空变量的类型是object。

这种方法每次都有效。:)