字符串转对象,数组 JSON.parse(), 输出不可见的对象JSON.stringify()

有时候会遇到下面的结构或者是对象结构的,get请求在query里传数组或者对象的

"['1213','34324']"

通常需要把字符串里的每项的单引号转换成双引号

const formattedStr = ids.replace(/'/g, '"');
"["1213","34324"]"

代码示例

  async removeByIdsGet(ids: string) { 
    
    console.log(ids, '00000', typeof ids);
    // const a = JSON.parse(ids)
    const formattedStr = ids.replace(/'/g, '"');
    const arr = JSON.parse(formattedStr);
    console.log(arr, '1111111', typeof arr);
    return this.userModel.deleteMany({ _id: { $in: arr } }).exec();
  }

简单示例对象

const jsonString = '{"name":"John","age":30,"city":"New York"}';
const obj = JSON.parse(jsonString);
console.log(obj);  // 输出: { name: 'John', age: 30, city: 'New York' }

这种对象也适用

const jsonArrayString = '[{"name":"John","age":30},{"name":"Jane","age":25}]';
const arr = JSON.parse(jsonArrayString);
console.log(arr);  // 输出: [{ name: 'John', age: 30 }, { name: 'Jane', age: 25 }]

数组:

const jsonArrayString = '["apple", "banana", "cherry"]';
const arr = JSON.parse(jsonArrayString);
console.log(arr);  // 输出: ['apple', 'banana', 'cherry']

使用 reviver 函数;

如果你想将所有的键名转换为大写:

const obj = JSON.parse(jsonString, function(key, value) {
  if (typeof key === 'string') {
    return [key.toUpperCase(), value];
  }
});

console.log(obj);  // 输出: { NAME: 'John', AGE: 30, CITY: 'New York' }

请注意,上面的例子中返回的是一个数组 [key.toUpperCase(), value],而不是 value,因此最终结果会是一个数组而不是对象。如果你想返回一个对象,你应该返回 {[key.toUpperCase()]: value}

const obj = JSON.parse(jsonString, function(key, value) {
  if (typeof key === 'string') {
    return {[key.toUpperCase()]: value};
  }
  return value;
});

console.log(obj);  // 输出: { NAME: 'John', AGE: 30, CITY: 'New York' }

JSON.stringify

相信大家都遇到过输出对象的时候会出现【data:data】的情况

使用JSON.stringify包裹对象就可以看到了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

每天吃饭的羊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值