2011-08-28 74 views
1

我想解析varialbe名成JSON字符串:使用Javascript變量

JSON:

{ 
    "items": [ 
     { 
      "id": "2000", 
      "buttons": [{ 
       "text": systemvar.continue, 
      }] 
     } 
} 

systemvar.continue在JavaScript中定義。

如何編寫JSON代碼以使用Javascript變量?

任何想法?

Best Kurt

+2

這只是無效的JSON。 –

回答

0

JSON是JavaScript語法的安全限制子集。如果您想允許任何 JavaScript語法(包括潛在不安全的語法),請使用eval()而不是JSON.parse()

3

如果systemvar.continue在JavaScript的定義,然後讓你的JSON有效像這樣:

{ 
    "items": [ 
     { 
      "id": "2000", 
      "buttons": [{ 
       "text": "continue", // <-- only pass the property name 
      }] 
     } 
} 

,然後訪問使用方括號的systemvar"continue"財產。

var result = systemvar[ json.items[0].buttons[0].text ]; 

當然,這是硬編碼,並假設你解析的JSON在一個名爲json變量被引用。我假設你正在遍歷結構,並且在某些時候會遇到text:"continue"。當你到達那裏時,將它作爲屬性名稱插入。

// in traversal 
systemvar[ val.text ]; 

我也建議您避免字continue因爲它是一個保留字,但它會用方括號裏的字符串工作。

0

我認爲你可以使用的是JSONP

的客戶端會有這樣的html代碼:

<script> 
function readData(json_arr) { 
    //`json_arr` will be the javascript array. 
    //do whatever you want to do with the array here. 
} 
</script> 
<script src="your_server.example.com/getData?jsonp=readData"></script> 

而服務器將返回:

readData(
{ 
    "items": [ 
     { 
      "id": "2000", 
      "buttons": [{ 
       "text": systemvar.continue, 
      }] 
     } 
    } 
) 

注意,這意味着你回來「JSON陣列」自動被執行瀏覽器的JavaScript引擎。