访问具有空格的JSON对象键 [英] Accessing JSON object keys having spaces

查看:101
本文介绍了访问具有空格的JSON对象键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下json对象:

I have following json object:

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

以下行正常工作:

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
alert(obj["No. of interfaces"]); //Return 'undefined'

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

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

推荐答案

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

The way to do this is via the bracket notation.

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

For更多信息请阅读:

For more info read out here:

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

这篇关于访问具有空格的JSON对象键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆