因此,在java腳本中,我需要從json中獲取密鑰的值。但是,如果我給鑰匙的對象點名稱,然後能夠得到它。在java腳本中獲取json密鑰的值(將密鑰名稱存儲在變量中並使用它)
<script>
var text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.employees[1].firstname + " " + obj.employees[1].lastName;
</script>
但是,如果我存儲在一個變量中鍵的名稱,並用它來獲取鍵,然後它不是爲我工作的價值。
<script>
var text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
obj = JSON.parse(text);
fn="firstname";
ln="lastname";
document.getElementById("demo").innerHTML =
obj.employees[1].fn + " " + obj.employees[1].ln;
</script>
我可以理解它正在尋找與fn和ln密鑰的問題。任何人都可以解釋我怎樣才能得到密鑰名稱存儲的變量的值。
使用括號符號來訪問在這種情況下https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors值 – Manish
它應該是'firstName'和不'firstname'。請注意,'n'是大寫 –