訪問JSON值假設我接收JSON對象從服務器因爲這如果鍵是數組元素
{ "asdf[zxcv]": "qwer" }
如何訪問asdf
,zxcv
,和在javascript qwer
,所以我可以使用這種方式的對象?
theobj.asdf[zxcv] = 'qwer'
訪問JSON值假設我接收JSON對象從服務器因爲這如果鍵是數組元素
{ "asdf[zxcv]": "qwer" }
如何訪問asdf
,zxcv
,和在javascript qwer
,所以我可以使用這種方式的對象?
theobj.asdf[zxcv] = 'qwer'
你需要將數據分配給一個變量,然後你可以使用對象鍵獲取這是:
之前的部分關鍵。這是一個例子。
var j = { "asdf[zxcv]": "qwer" };
console.log(Object.keys(j)); //["asdf[zxcv]"]
console.log(j); //{asdf[zxcv]: "qwer"}
括號符號不在JSON RFC中。你只能以字符串的形式閱讀它。
var simpleObj = {
"simpleKey": "simpleValue"
}
console.log(simpleObj)
var advObj = {
"advKey[1]": "advValue"
}
console.log(JSON.parse(advObj)); // SyntaxError
console.log(advObj.advKey[1]) // TypeError
console.log(advObj["advKey[1]"]) // can only read as string
您將需要重構源JSON成更有意義的,所以你可以在常規的JavaScript方式訪問值。
運行下面的代碼片段來檢查你如何解決這個問題:
var x = '{ "asdf[zxcv]": "qwer" }';
var y = JSON.parse(x);
var result = Object.keys(y).reduce(function(result, key) {
var parentKey = key.substring(0, key.indexOf("["));
var innerKey = /[a-z]+\[([a-z]+)\]/i.exec(key)[1];
if (!result.hasOwnProperty(key))
result[parentKey] = {};
result[parentKey][innerKey] = y[key];
return result;
}, {});
document.getElementById("structure").textContent = JSON.stringify(result);
var zxcv = result["asdf"]["zxcv"];
document.getElementById("someValue").textContent = zxcv;
<h2>Refactored data structure as nested objects:</h2>
<div id="structure"></div>
<h2>Accessing some value: result["asdf"]["zxcv"] or result.asdf.zxcv</h2>
<div id="someValue"></div>
這是所有關於創建嵌套對象來表示在源JSON性質代表的概念關聯的關聯鍵array ...
這是訪問所有元素而不重建對象的方法之一。
jQuery.each(JSON.parse('{ "asdf[zxcv]": "qwer" }'), function(index, value) {
var i = index;// i = "asdf[zxcv]"
var v = value;// v = "qwer"
var iOfInnerValue = (/\[(.*?)\]/g).exec(i)[1];// innerValue = "zxcv"
var iOfOuterValue = index.replace("["+(/\[(.*?)\]/g).exec(i)[1]+"]",""); // outerValue = "asdf"
});
您需要在語法上創建關鍵字符串,然後才能訪問它的值。 –
你想要訪問'zxcv'是什麼意思?除非你正在考慮ES6 WeakMap或其他東西,否則這是沒有意義的。 – Andy
在你的例子中,'zxcv'不是一個變量,而是'asdf'的關聯關鍵字。 – GiamPy