最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get a JSON value from a variable - Stack Overflow

programmeradmin2浏览0评论

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

so when I do

var a = data.243232.id; alert(a); // it gives me 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.

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

so when I do

var a = data.243232.id; alert(a); // it gives me 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.

Share Improve this question asked May 13, 2011 at 5:20 druveendruveen 1,6913 gold badges15 silver badges32 bronze badges 1
  • Please accept a correct answer by clicking the green question mark beside the answer that was the best – austinbv Commented May 15, 2011 at 3:12
Add a comment  | 

2 Answers 2

Reset to default 11

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

Remember all objects in JS are really just associative arrays.

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

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

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.

As for you addition

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

Will work

Use data[c].id.

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

发布评论

评论列表(0)

  1. 暂无评论