[英]Unable to remove a key value pair from JSON string?
On doing console.log(data.toString())
, I get the following output:在执行
console.log(data.toString())
,我得到以下输出:
{
"cid":"9333227",
"status" : 30,
"user" : "user1"
}
On doing console.log(data['cid'])
before performing delete, I get undefined
as the output在执行删除之前执行
console.log(data['cid'])
,我得到undefined
作为输出
I want to remove the cid
key value pair such that the console.log(data.toString())
should generate the following output:我想删除
cid
键值对,以便console.log(data.toString())
应生成以下输出:
{
"status" : 30,
"user" : "user1"
}
I am doing delete data['cid']
and then doing console.log(data.toString())
.我正在做
delete data['cid']
然后做console.log(data.toString())
。 However, it is still printing the original json但是,它仍然打印原始json
{
"cid":"9333227",
"status" : 30,
"user" : "user1"
}
If you run data.toString())
, and get the output you got, means that data
is not an object.如果你运行
data.toString())
,并得到你得到的输出,意味着data
不是一个对象。 It's likely a string.它很可能是一个字符串。
If you run:如果你运行:
"hello".toString();
you get "hello".你得到“你好”。
If you run:如果你运行:
delete "hello".foo
You are deleting a non-existant property on the string, which works without error.您正在删除字符串上不存在的属性,该属性可以正常工作。 It doesn't change the contents of the string.
它不会改变字符串的内容。
So I think you don't have an object, you have a JSON string.所以我认为你没有对象,你有一个 JSON 字符串。 To mutate it, you need to first parse it:
要对其进行变异,您需要先解析它:
const obj = JSON.parse(data);
delete obj.cid;
console.log(obj);
If you need to turn it back into a JSON string, you can use JSON.stringify()
.如果需要将其转回 JSON 字符串,可以使用
JSON.stringify()
。
let jsonobj = {
"cid": "933227",
"status": 30,
"user": "user1",
}
delete jsonobj['cid']
console.log(JSON.stringify(jsonobj));
Try JSON.stringify() instead of .toString()尝试 JSON.stringify() 而不是 .toString()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.