isJsonString('{ "Id": 1, "Name": "Coke" }')
应该是正确的
isJsonString('foo')
isJsonString('<div>foo</div>')
应该为假。
我正在寻找一种不使用try/catch的解决方案,因为我将调试器设置为“在所有错误上中断”,这导致它在无效的JSON字符串上中断。
isJsonString('{ "Id": 1, "Name": "Coke" }')
应该是正确的
isJsonString('foo')
isJsonString('<div>foo</div>')
应该为假。
我正在寻找一种不使用try/catch的解决方案,因为我将调试器设置为“在所有错误上中断”,这导致它在无效的JSON字符串上中断。
当前回答
我想我应该在一个实际的例子中加入我的方法。我在处理从Memjs输入和输出的值时使用了类似的检查,所以即使保存的值可能是字符串,数组或对象,Memjs期望的是字符串。该函数首先检查键/值对是否已经存在,如果存在,则进行预检查,以确定值是否需要在返回之前进行解析:
function checkMem(memStr) {
let first = memStr.slice(0, 1)
if (first === '[' || first === '{') return JSON.parse(memStr)
else return memStr
}
否则,调用回调函数来创建值,然后检查结果,看看值是否需要在进入Memjs之前进行字符串化,然后返回回调的结果。
async function getVal() {
let result = await o.cb(o.params)
setMem(result)
return result
function setMem(result) {
if (typeof result !== 'string') {
let value = JSON.stringify(result)
setValue(key, value)
}
else setValue(key, result)
}
}
完整的代码如下。当然,这种方法假定数组/对象输入和输出的格式是正确的(例如,“{key: 'testkey']”之类的事情永远不会发生,因为在键/值对到达这个函数之前,所有正确的验证都已经完成了)。而且你只是在memjs中输入字符串,而不是整数或其他非对象/数组类型。
async function getMem(o) {
let resp
let key = JSON.stringify(o.key)
let memStr = await getValue(key)
if (!memStr) resp = await getVal()
else resp = checkMem(memStr)
return resp
function checkMem(memStr) {
let first = memStr.slice(0, 1)
if (first === '[' || first === '{') return JSON.parse(memStr)
else return memStr
}
async function getVal() {
let result = await o.cb(o.params)
setMem(result)
return result
function setMem(result) {
if (typeof result !== 'string') {
let value = JSON.stringify(result)
setValue(key, value)
}
else setValue(key, result)
}
}
}
其他回答
从原型框架字符串。isJSON定义
/**
* String#isJSON() -> Boolean
*
* Check if the string is valid JSON by the use of regular expressions.
* This security method is called internally.
*
* ##### Examples
*
* "something".isJSON();
* // -> false
* "\"something\"".isJSON();
* // -> true
* "{ foo: 42 }".isJSON();
* // -> false
* "{ \"foo\": 42 }".isJSON();
* // -> true
**/
function isJSON() {
var str = this;
if (str.blank()) return false;
str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@');
str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
return (/^[\],:{}\s]*$/).test(str);
}
这个版本可以用来传递一个字符串对象
function isJSON(str) {
if ( /^\s*$/.test(str) ) return false;
str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@');
str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
return (/^[\],:{}\s]*$/).test(str);
}
function isJSON(str) { if ( /^\s*$/.test(str) ) return false; str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'); str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'); str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, ''); return (/^[\],:{}\s]*$/).test(str); } console.log ("this is a json", isJSON( "{ \"key\" : 1, \"key2@e\" : \"val\"}" ) ) console.log("this is not a json", isJSON( "{ \"key\" : 1, \"key2@e\" : pippo }" ) )
你可以使用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将抛出异常。
我想我知道你为什么不想这么做。但也许试着去抓!;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; }};
由于这是尽可能封装的,它可能不会在错误时中断。
isValidJsonString - check for valid json string JSON data types - string, number, object (JSON object), array, boolean, null (https://www.json.org/json-en.html) falsy values in javascript - false, 0, -0, 0n, ", null, undefined, NaN - (https://developer.mozilla.org/en-US/docs/Glossary/Falsy) JSON.parse works well for number , boolean, null and valid json String won't raise any error. please refer example below JSON.parse(2) // 2 JSON.parse(null) // null JSON.parse(true) // true JSON.parse('{"name":"jhamman"}') // {name: "jhamman"} JSON.parse('[1,2,3]') // [1, 2, 3] break when you parse undefined , object, array etc it gave Uncaught SyntaxError: Unexpected end of JSON input . please refer example below JSON.parse({}) JSON.parse([]) JSON.parse(undefined) JSON.parse("jack")
function isValidJsonString(jsonString){
if(!(jsonString && typeof jsonString === "string")){
return false;
}
try{
JSON.parse(jsonString);
return true;
}catch(error){
return false;
}
}
这个答案降低了trycatch语句的代价。
我使用JQuery来解析JSON字符串,我使用trycatch语句来处理异常,但是对于不可解析的字符串抛出异常会降低我的代码,所以我使用简单的Regex来检查字符串,如果它是一个可能的JSON字符串,或者不是通过检查它的语法来羽毛,然后我使用常规的方式通过JQuery解析字符串:
if (typeof jsonData == 'string') {
if (! /^[\[|\{](\s|.*|\w)*[\]|\}]$/.test(jsonData)) {
return jsonData;
}
}
try {
jsonData = $.parseJSON(jsonData);
} catch (e) {
}
我将前面的代码包装在递归函数中,以解析嵌套的JSON响应。