如何在不使用Try/Catch的情况下检查字符串在JavaScript中是否是有效的JSON字符串
比如:如何在不使用Try/Catch的情况下检查字符串在JavaScript中是否是有效的JSON字符串,javascript,json,Javascript,Json,比如: var jsonString = '{ "Id": 1, "Name": "Coke" }'; //should be true IsJsonString(jsonString); //should be false IsJsonString("foo"); IsJsonString("<div>foo</div>") if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@'). replac
var jsonString = '{ "Id": 1, "Name": "Coke" }';
//should be true
IsJsonString(jsonString);
//should be false
IsJsonString("foo");
IsJsonString("<div>foo</div>")
if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
//the json is ok
}else{
//the json is not ok
}
var jsonString='{“Id”:1,“Name”:“Coke”}';
//应该是真的
IsJsonString(jsonString);
//应该是假的
IsJsonString(“foo”);
IsJsonString(“foo”)
解决方案不应包含try/catch。我们中的一些人打开“在所有错误上中断”,他们不喜欢调试器中断那些无效的JSON字符串。使用JSON解析器,如
JSON。parse
:
function IsJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
在prototypeJS中,我们有方法。你可以试试。甚至可能有帮助
"something".isJSON();
// -> false
"\"something\"".isJSON();
// -> true
"{ foo: 42 }".isJSON();
// -> false
"{ \"foo\": 42 }".isJSON();
// -> true
您可以使用javascript函数来验证它是否有效 e、 g 或者,您可以从以下位置使用
JSON.parse
函数:
希望这有帮助
警告:eval()
如果有人添加了恶意JS代码,那么它是危险的,因为它会执行它。确保JSON字符串是可信的,即您从可信的来源获得它
编辑对于我的第一个解决方案,建议这样做
try {
json = eval("{" + jsonString + "}");
} catch (exception) {
//It's advisable to always catch an exception since eval() is a javascript executor...
json = null;
}
保证质量。如果jsonString
不是纯JSON,则eval将抛出异常。首先是注释。问题是没有使用try/catch
如果你不介意使用它,请阅读下面的答案。 在这里,我们只需使用regexp检查
JSON
字符串,它在大多数情况下都能工作,而不是在所有情况下
请看一下中的第450行
有一个用于检查有效JSON的regexp,类似于:
var jsonString = '{ "Id": 1, "Name": "Coke" }';
//should be true
IsJsonString(jsonString);
//should be false
IsJsonString("foo");
IsJsonString("<div>foo</div>")
if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
//the json is ok
}else{
//the json is not ok
}
编辑:新版本的json2.js进行了比上述更高级的解析,但仍然基于regexp替换(来自)可能有用:
function parseJson(code)
{
try {
return JSON.parse(code);
} catch (e) {
return code;
}
}
function parseJsonJQ(code)
{
try {
return $.parseJSON(code);
} catch (e) {
return code;
}
}
var str = "{\"a\":1,\"b\":2,\"c\":3,\"d\":4,\"e\":5}";
alert(typeof parseJson(str));
alert(typeof parseJsonJQ(str));
var str_b = "c";
alert(typeof parseJson(str_b));
alert(typeof parseJsonJQ(str_b));
输出:
IE7:字符串,对象,字符串,字符串
function get_json(txt)
{ var data
try { data = eval('('+txt+')'); }
catch(e){ data = false; }
return data;
}
CHROME:对象,对象,字符串,字符串
function get_json(txt)
{ var data
try { data = eval('('+txt+')'); }
catch(e){ data = false; }
return data;
}
如果有错误,则返回false
如果没有错误,请返回json数据我知道我问这个问题晚了3年,但我想插嘴
虽然Gumbo的解决方案工作得很好,但它并不能处理少数情况,在这些情况下,JSON.parse({非JSON的东西})
我还希望同时返回解析后的JSON,这样调用代码就不必再次调用JSON.parse(jsonString)
这似乎很适合我的需要:
function tryParseJSON (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;
};
这个答案可以降低trycatch语句的成本
我使用JQuery解析JSON字符串,使用trycatch语句处理异常,但为不可解析的字符串抛出异常会减慢代码的速度,因此我使用简单的正则表达式检查字符串是否可能是JSON字符串,而无需检查其语法,然后我使用常规方法,使用JQuery解析字符串:
if (typeof jsonData == 'string') {
if (! /^[\[|\{](\s|.*|\w)*[\]|\}]$/.test(jsonData)) {
return jsonData;
}
}
try {
jsonData = $.parseJSON(jsonData);
} catch (e) {
}
我将前面的代码包装在递归函数中,以解析嵌套的JSON响应
我使用了一个非常简单的方法来检查字符串是否是有效的JSON
function testJSON(text){
if (typeof text!=="string"){
return false;
}
try{
JSON.parse(text);
return true;
}
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,因为null变量的类型是object
这种方法每次都有效。:)
用法:isJSON({})
将为false
,isJSON({}')
将为true
要检查某物是否是数组
或对象
(已解析的JSON):
用法:
isAO({})
将是true
,isAO({}')
将是false
来自原型框架String.isJSON
定义
这就是可以用来传递字符串对象的版本
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);
}
函数isJSON(str){
if(/^\s*$/.test(str))返回false;
str=str.replace(/\\(?:[“\\\\/bfnrt]| u[0-9a-fA-F]{4})/g,'@');
str=str.replace(/“[^”\\\n\r]*“|真|假|空|-?\d+(?:\。\d*)?(?:[eE][+\-]?\d+?/g,”);
str=str.replace(/(?:^.:,)(?:\s*\[)+/g',);
返回(/^[\],:{}\s]*$/).test(str);
}
console.log(“这是一个json”,isJSON(“{\”key\”:1,\”key2@e\“:\“val\”}”))
log(“这不是一个json”,isJSON(“{\”key\”:1,\”key2@e\“:pippo}”)
我想我知道你为什么要避免这样做。但也许可以尝试并抓住!==试着抓住;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; }};
由于它尽可能密封,因此不会因错误而破裂。
var jsonstring='[{“ConnectionString”:“aaaaa”,“Server”:“ssssss”}];
if(((x)=>{try{JSON.parse(x);返回true;}catch(e){return false}})(jsonstring)){
document.write(“valide json”)
}否则{
document.write(“无效json”)
}
我从开头的注释推断,用例描述了响应是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。以下是typescript版本:
JSONTryParse(input: any) {
try {
//check if the string exists
if (input) {
var o = JSON.parse(input);
//validate the result too
if (o && o.constructor === Object) {
return o;
}
}
}
catch (e: any) {
}
return false;
};
希望这也适用于您哦,您一定可以使用try-catch检查它是否是有效的JSON
if (expected_json.id === undefined){
// not a json
}
else{
// json
}
在Firfox Quantom 60.0.1上测试
if (expected_json.id === undefined){
// not a json
}
else{
// json
}
在函数中使用函数来测试JSON,并使用该输出来验证字符串。听到一个例子
function myfunction(text){
//function for validating json string
function testJSON(text){
try{
if (typeof text!=="string"){
return false;
}else{
JSON.parse(text);
return true;
}
}
catch (error){
return false;
}
}
//content of your real function
if(testJSON(text)){
console.log("json");
}else{
console.log("not json");
}
}
//use it as a normal function
myfunction('{"name":"kasun","age":10}')
这里是我的工作代码:
function IsJsonString(str) {
try {
var json = JSON.parse(str);
return (typeof json === 'object');
} catch (e) {
return false;
}
}
正在使用的函数在我的情况下不起作用。我试图验证它的json输出总是返回false。幸运的是,效果更好:
var test = false;
$('body').on('DOMSubtreeModified', '.resultWrap', function() {
if (!test) {
var resultWrap = "{" + $('#graphiql .resultWrap').text().split("{").pop();
if isJSON(resultWrap) {test = !test;}
console.log(resultWrap);
console.log(resultWrap.isJSON());
}
});
样本输出:
THREE.WebGLRenderer 79
draw.js:170 {xxxxxxxxxx
draw.js:170 false
draw.js:170 {xxxxxxxxxx
draw.js:170 false
draw.js:170 {xxxxxxxxxx
draw.js:170 false
draw.js:170 {xxxxxxxxxx
draw.js:170 false
draw.js:170 {
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793,
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793, "time": 1570751209006,
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793, "time": 1570751209006, "tick": 156,
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793, "time": 1570751209006, "tick": 156, "tickr": 1.56,
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793, "time": 1570751209006, "tick": 156, "tickr": 1.56, "fps": 41.666666666666664,
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793, "time": 1570751209006, "tick": 156, "tickr": 1.56, "fps": 41.666666666666664, "width": 396.984,
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793, "time": 1570751209006, "tick": 156, "tickr": 1.56, "fps": 41.666666666666664, "width": 396.984, "height": 327
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793, "time": 1570751209006, "tick": 156, "tickr": 1.56, "fps": 41.666666666666664, "width": 396.984, "height": 327}
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793, "time": 1570751209006, "tick": 156, "tickr": 1.56, "fps": 41.666666666666664, "width": 396.984, "height": 327}
draw.js:170 true
对于那些喜欢李的人
THREE.WebGLRenderer 79
draw.js:170 {xxxxxxxxxx
draw.js:170 false
draw.js:170 {xxxxxxxxxx
draw.js:170 false
draw.js:170 {xxxxxxxxxx
draw.js:170 false
draw.js:170 {xxxxxxxxxx
draw.js:170 false
draw.js:170 {
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793,
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793, "time": 1570751209006,
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793, "time": 1570751209006, "tick": 156,
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793, "time": 1570751209006, "tick": 156, "tickr": 1.56,
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793, "time": 1570751209006, "tick": 156, "tickr": 1.56, "fps": 41.666666666666664,
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793, "time": 1570751209006, "tick": 156, "tickr": 1.56, "fps": 41.666666666666664, "width": 396.984,
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793, "time": 1570751209006, "tick": 156, "tickr": 1.56, "fps": 41.666666666666664, "width": 396.984, "height": 327
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793, "time": 1570751209006, "tick": 156, "tickr": 1.56, "fps": 41.666666666666664, "width": 396.984, "height": 327}
draw.js:170 false
draw.js:170 { "PI": 3.141592653589793, "time": 1570751209006, "tick": 156, "tickr": 1.56, "fps": 41.666666666666664, "width": 396.984, "height": 327}
draw.js:170 true
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);
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;
}
}
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
});
if (expected_json.id === undefined){
// not a json
}
else{
// json
}
function isValidJsonString(jsonString){
if(!(jsonString && typeof jsonString === "string")){
return false;
}
try{
JSON.parse(jsonString);
return true;
}catch(error){
return false;
}
}
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)
}
}
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)
}
}
}