javascript 如何从变量中获取 JSON 值

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

How to get a JSON value from a variable

javascriptjsonvariables

提问by druveen

suppose I have {"data": {"243232": {"id": "testid","name": "test" } }}

假设我有 {"data": {"243232": {"id": "testid","name": "test" } }}

so when I do

所以当我做

var a = data.243232.id; alert(a);// it gives me testid.

var a = data.243232.id; alert(a);// 它给了我testid.

but when I do like

但是当我喜欢

    var c = 243232; 
    var d = data.c.id;
    alert(d) //it gives as undefined.

so how to get correct value when i alert d in above case thanks.

那么当我在上述情况下提醒 d 时如何获得正确的值,谢谢。

回答by austinbv

Use the other notation var a = data['243232'].id

使用其他符号 var a = data['243232'].id

Remember all objects in JS are really just associative arrays.

请记住,JS 中的所有对象实际上只是关联数组。

Object keys just a variable in js and thus require proper naming

对象键只是 js 中的一个变量,因此需要正确命名

the variable naming rules are.

变量命名规则是。

  • The first character must be a letter (either uppercase or lowercase) or an underscore (_), or a dollar sign ($).
  • Subsequent characters can be letters, numbers, underscores, or dollar signs in JavaScript Variables.
  • The JavaScript Variable name can't be a reserved word of JavaScript, see details of JavaScript Reserved Characters
  • 第一个字符必须是字母(大写或小写)或下划线 (_) 或美元符号 ($)。
  • 后续字符可以是 JavaScript 变量中的字母、数字、下划线或美元符号。
  • JavaScript 变量名不能是 JavaScript 的保留字,详见 JavaScript 保留字符

JSON normally uses an eval() function to turn the string into a data-structure. This allows for incorrect keys. If you want to reference an improper key, you need to use the associative array method.

JSON 通常使用 eval() 函数将字符串转换为数据结构。这允许不正确的密钥。如果要引用不正确的键,则需要使用关联数组方法。

As for you addition

至于你加

var c = 243232; 
var d = data[c].id;
alert(d) //it gives as undefined.

Will work

将工作

回答by alex

Use data[c].id.

使用data[c].id.

In JavaScript, .propis syntactic sugar for ["prop"]. The bracket notation allows you to use values which would be invalid when using .(such as background-image) and variables.

在 JavaScript 中,.prop["prop"]. 括号表示法允许您使用在使用.(例如background-image)和变量时无效的值。