小兔网

判断方法:首先使用“JSON.parse(str)”语句解析指定数据str;然后使用“if(typeof obj =='object'&&obj)”语句判断解析后数据的类型是否为“object”类型;如果是,则str数据是json格式。

javascript怎么判断是否是json格式

本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。

js判断字符串是否为JSON格式

不能简单地使用来判断字符串是否是JSON格式:

function isJSON(str) {    if (typeof str == 'string') {        try {            JSON.parse(str);            return true;        } catch(e) {            console.log(e);            return false;        }    }    console.log('It is not a string!')    }

以上try/catch的确实不能完全检验一个字符串是JSON格式的字符串,有许多例外:

JSON.parse('123'); // 123JSON.parse('{}'); // {}JSON.parse('true'); // trueJSON.parse('"foo"'); // "foo"JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]JSON.parse('null'); // null

我们知道,JS中的数据类型分为:字符串、数字、布尔、数组、对象、Null、Undefined。

我们可以使用如下的方法来判断:

function isJSON(str) {    if (typeof str == 'string') {        try {            var obj=JSON.parse(str);            if(typeof obj == 'object' && obj ){                return true;            }else{                return false;            }        } catch(e) {            console.log('error:'+str+'!!!'+e);            return false;        }    }    console.log('It is not a string!')}console.log('123 is json? ' + isJSON('123'))console.log('{} is json? ' + isJSON('{}'))console.log('true is json? ' + isJSON('true'))console.log('foo is json? ' + isJSON('"foo"'))console.log('[1, 5, "false"] is json? ' + isJSON('[1, 5, "false"]'))console.log('null is json? ' + isJSON('null'))console.log('["1{211323}","2"] is json? ' + isJSON('["1{211323}","2"]'))console.log('[{},"2"] is json? ' + isJSON('[{},"2"]'))console.log('[[{},{"2":"3"}],"2"] is json? ' + isJSON('[[{},{"2":"3"}],"2"]'))

运行结果为:

> "123 is json? false"> "{} is json? true"> "true is json? false"> "foo is json? false"> "[1, 5, "false"] is json? true"> "null is json? false"> "["1{211323}","2"] is json? true"> "[{},"2"] is json? true"> "[[{},{"2":"3"}],"2"] is json? true"

所以得出以下结论:

JSON.parse() 方法用来解析JSON字符串,json.parse()将字符串转成json对象

如果JSON.parse能够转换成功;并且转换后的类型为object 且不等于 null,那么这个字符串就是JSON格式的字符串。

JSON.parse():

JSON 通常用于与服务端交换数据。

在接收服务器数据时一般是字符串。

我们可以使用 JSON.parse() 方法将数据转换为 JavaScript 对象。

语法:

JSON.parse(text[, reviver])

参数说明:

  • text:必需, 一个有效的 JSON 字符串。

  • reviver: 可选,一个转换结果的函数, 将为对象的每个成员调用此函数。

解析前要确保你的数据是标准的 JSON 格式,否则会解析出错。

更多编程相关知识,请访问:编程视频!!

以上就是javascript怎么判断是否是json格式的知识。速戳>>知识兔学习精品课!