Javascript 访问具有空格的 JSON 对象键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10311361/
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-24 00:48:43  来源:igfitidea点击:

Accessing JSON object keys having spaces

javascriptjson

提问by Usman

I have following json object:

我有以下 json 对象:

{ "id": "109",
  "No. of interfaces": "4" }

Following lines work fine:

以下几行工作正常:

alert(obj.id);
alert(obj["id"]);

But if keys have spaces then I cannot access their values e.g.

但是如果键有空格,那么我无法访问它们的值,例如

alert(obj."No. of interfaces"); //Syntax error

How can I access values, whose key names have spaces? Is it even possible?

如何访问键名有空格的值?甚至有可能吗?

回答by Joseph

The way to do this is via the bracket notation.

这样做的方法是通过括号表示法。

var test = {
    "id": "109",
    "No. of interfaces": "4"
}
alert(test["No. of interfaces"]);

For more info read out here:

有关更多信息,请阅读此处:

回答by Laser42

The answer of Pardeep Jain can be useful for static data, but what if we have an array in JSON?

Pardeep Jain 的答案对静态数据很有用,但是如果我们有一个 JSON 数组呢?

For example, we have i values and get the value of id field

例如,我们有 i 个值并获取 id 字段的值

alert(obj[i].id); //works!

But what if we need key with spaces?

但是如果我们需要带空格的键怎么办?

In this case, the following construction can help (without point between [] blocks):

在这种情况下,以下构造可以提供帮助(在 [] 块之间没有点):

alert(obj[i]["No. of interfaces"]); //works too!