有时候会遇到下面的结构或者是对象结构的,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包裹对象就可以看到了