Home > Web Front-end > JS Tutorial > body text

How to determine whether jquery is in json format

coldplay.xixi
Release: 2023-01-04 09:36:35
Original
3990 people have browsed it

jquery判断是否是json格式的方法:首先使用jquery的【parseJSON()】方法,将字符串转为json对象,并用try catch语句捕获错误;然后如果没有异常,则是json格式。

How to determine whether jquery is in json format

本教程操作环境:windows7系统、jquery1.12版本,Dell G3电脑。

推荐:jquery视频教程

jquery判断是否是json格式的方法:

思路:使用jquery的parseJSON()方法,将字符串转为json对象,并用try catch语句捕获错误,没有异常,则是json格式,否则不是。

function fun (str) {
    try{
        $.parseJSON(str)
        return true
    }catch (e) {
        return false
    } 
}
Copy after login

测试:

How to determine whether jquery is in json format

jquery parseJSON()

$.parseJSON()函数用于将符合标准格式的的JSON字符串转为与之对应的JavaScript对象。

注意:传入格式有误的 JSON 字符串可能导致抛出异常。

"{test: 1}"
//test是属性名称,必须加双引号
"{'test': 1}"
//test是属性名称,必须用双引号(不能用单引号)
"'test'"
//test是属性名称,必须用双引号(不能用单引号)
".1"
//number 必须以数字开头; "0.1" 将是有效的
"undefined"
//undefined 不能表示一个 JSON 字符串; null可以
"NaN"
//NaN 不能表示一个 JSON 字符串; 用Infinity直接表示无限也是不允许的
Copy after login

JSON标准不允许"控制字符"如制表符或换行符,例如:

// 多数情况下,它会抛出一个错误,因为JS解析器会将字符串中的\t或\n等转义直接视作字面值,起到Tab或换行的效果。
$.parseJSON('{"testing":"1\t2\n3"}')
Copy after login

正确写法应该如下(使用两个反斜杠,以免被JS解析器直接转义\t或\n):

$.parseJSON('{"testing":"1\\t2\\n3"}')
Copy after login

相关免费学习推荐:javascript(视频)

The above is the detailed content of How to determine whether jquery is in json format. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!