Skip to content

devParseJson 解析json字符串

devParseJson 是一个安全的 JSON 字符串解析工具函数,用于解析传入的字符串为对象。当解析失败(如传入非法 JSON、空字符串等)时, 会返回预设的默认对象,避免程序因解析错误而中断。 适用于需要防止 JSON.parse 抛错的场景,例如从缓存、接口、用户输入中读取数据时。

devParseJson 有两个入参,第一个参数为要解析的json字符信息,第二个参数为解析失败后返回的对象信息,默认为空对象。

使用示例

ts
import {devParseJson} from "devecoui-plus"

const jsonStr = '{"name": "张三", "age": 25}';
const result1 = devParseJson(jsonStr);
// 输出:{ name: '张三', age: 25 }

const brokenStr = '{name: "张三", age: 25}'; // 非合法 JSON 格式
const result2 = devParseJson(brokenStr, { name: '默认用户', age: 0 });
// 输出:{ name: '默认用户', age: 0 }
// 同时控制台会报错提示解析失败

const result3 = devParseJson('', { status: 'empty' });
// 输出:{ status: 'empty' }