写一个方法把对象和字符串互转

/**
 * 在对象和字符串之间进行转换。
 *
 * @param {Object|string} data 要转换的数据。
 * @param {boolean} [stringify=false] 如果为 true,则将对象转换为字符串。如果为 false 或未定义,则将字符串转换为对象。
 * @returns {Object|string|null} 转换后的数据,如果转换失败则返回 null。
 */
function convertBetweenObjectAndString(data, stringify = false) {
  if (stringify) {
    // 对象转字符串
    try {
      return JSON.stringify(data);
    } catch (error) {
      console.error("对象转字符串失败:", error);
      return null;
    }
  } else {
    // 字符串转对象
    try {
      if (typeof data === 'string' && data.trim() !== '') { // 处理空字符串情况
        return JSON.parse(data);
      } else if (data === null || typeof data === 'undefined' || (typeof data === 'string' && data.trim() === '')) {
        return null; // 或返回 {}  取决于你的需求,空字符串是返回null还是空对象
      } else {
        return data; // 如果不是字符串,直接返回原始数据
      }
    } catch (error) {
      console.error("字符串转对象失败:", error);
      return null;
    }
  }
}


// 示例用法:

// 对象转字符串
const myObject = { name: "John Doe", age: 30 };
const jsonString = convertBetweenObjectAndString(myObject, true);
console.log(jsonString); // 输出: '{"name":"John Doe","age":30}'

// 字符串转对象
const jsonString2 = '{"name":"Jane Doe","age":25}';
const myObject2 = convertBetweenObjectAndString(jsonString2);
console.log(myObject2); // 输出: {name: 'Jane Doe', age: 25}

// 处理错误情况
const invalidJsonString = '{"name":"Invalid JSON'; // 无效的 JSON 字符串
const parsedObject = convertBetweenObjectAndString(invalidJsonString);
console.log(parsedObject); // 输出: null

// 处理空字符串
const emptyString = "";
const parsedObject2 = convertBetweenObjectAndString(emptyString);
console.log(parsedObject2); // 输出: null


// 非字符串情况
const num = 123;
const resultNum = convertBetweenObjectAndString(num);
console.log(resultNum); // 输出: 123


const nullValue = null;
const resultNull = convertBetweenObjectAndString(nullValue);
console.log(resultNull); // 输出: null

这个改进的版本包含以下增强功能:

  • 错误处理: 使用 try...catch 块来捕获 JSON.parseJSON.stringify 中的潜在错误,并在发生错误时返回 null 并打印错误消息到控制台。
  • 空字符串处理: 增加了对空字符串的处理,防止JSON.parse报错。根据你的需求,你可以选择返回 null{}
  • 非字符串输入的处理: 如果输入不是字符串类型,则直接返回原始输入,避免不必要的处理和潜在的错误。
  • 更清晰的注释和示例: 添加了更详细的注释来解释函数的功能和用法,并提供了更全面的示例来演示如何处理各种情况,包括有效和无效的 JSON 字符串、空字符串、以及非字符串输入。

这个版本更加健壮,可以处理各种边缘情况,并提供更好的错误处理,使其更适合在生产环境中使用。

posted @   王铁柱6  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示