javascript 表示 JSON 对象属性未定义,尽管它不是

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44729266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:42:29  来源:igfitidea点击:

javascript says JSON object property is undefined although it's not

javascriptjsonobjectpropertiesundefined

提问by steady_progress

I have a json-object, which I print to the screen (using alert()-function):

我有一个 json 对象,我将它打印到屏幕上(使用 alert() 函数):

alert(object);

Here is the result:

结果如下:

enter image description here

在此处输入图片说明

Then I want to print the value of the id to the screen:

然后我想将 id 的值打印到屏幕上:

    alert(object["id"]); 

The result is this:

结果是这样的:

enter image description here

在此处输入图片说明

As you can see, the value of key "id" is not(!!!) undefined.

如您所见,键“id”的值不是(!!!)未定义的。

What the hell is going on here?!

这到底是怎么回事?!

回答by Yuval Perelman

Looks like your json object is not really an object, it's a json string. in order to use it as an object you will need to use a deserialization function like JSON.parse(obj). Many frameworks have their own implementation to how to deserialize a JSON string.
When you try to do alert(obj)with a real object the result would be [object Object] or something like that

看起来您的 json 对象并不是真正的对象,而是一个 json 字符串。为了将它用作对象,您需要使用像JSON.parse(obj). 许多框架都有自己的如何反序列化 JSON 字符串的实现。
当您尝试alert(obj)使用真实对象时,结果将是 [object Object] 或类似的东西

回答by Mahmoud Ali Kassem

Your JSON is not parsed, so in order for JavaScript to be able to access it's values you should parse it first as in line 1:

你的 JSON 没有被解析,所以为了让 JavaScript 能够访问它的值,你应该首先像第 1 行一样解析它:

var result = JSON.parse(object);
alert(result.id);

After your JSON Objected is already parsed, then you can access it's values as following:

在您的 JSON Objected 已经被解析后,您可以访问它的值,如下所示:

alert(result.id);

回答by Pritam Banerjee

You will need to assign that to a varand then access it.

您需要将其分配给 avar然后访问它。

var object = {id: "someId"};
console.log(object);
alert(object["id"]);

回答by Kevin Mencos

In JavaScript, object properties can be accessed with . operator or with associative array indexing using []. I.e. object.property is equivalent to object["property"]

在 JavaScript 中,可以使用 . 运算符或使用关联数组索引[]。即 object.property 相当于object["property"]

You can try:

你可以试试:

var obj = JSON.parse(Object);
alert(obj.id);