parseJsonNoError【解析JSON字符串】
描述
解析 JSON 字符串,防止抛出异常,解析成功返回正确的解析数据,出异常返回 null
# 1.示例
import { parseJsonNoError } from 'sf-utils2'
const userJson = '{"name":"bianpengfei","age":26}'
const userJsonError = '{1}2324'
parseJsonNoError(userJson) // 解析正确:{name: 'bianpengfei', age: 26}
parseJsonNoError(userJsonError) // 解析错误:返回 null
1
2
3
4
5
6
2
3
4
5
6
# 2.入参说明
| 参数 | 说明 | 类型 | 是否必填 | 默认值 |
|---|---|---|---|---|
| str | JSON 字符串 | string | 是 |
# 3.源码
/**
* json解析,防止抛出异常
* @param str
* @returns {null|any}
*/
function parseJsonNoError(str = '') {
try {
return JSON.parse(str)
} catch (e) {
return null
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
上次更新: 2024/01/08, 21:47:25