2011-08-28 73 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引擎。