JSON with Javascript variable

JSON with Javascript variable

本文关键字:variable Javascript with JSON      更新时间:2023-09-26

我想把一个变量名解析成一个JSON字符串:

JSON:

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

systemvar。continue是在Javascript中定义的。

我如何编写JSON代码来使用Javascript变量?

任何想法?

最佳Kurt

如果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这个词,因为它是一个保留词,尽管它可以与方括号中的字符串一起使用。

JSON是JavaScript语法的一个安全、受限制的子集。如果您希望允许任何 JavaScript语法,包括可能不安全的语法,请使用eval()而不是JSON.parse()

我认为你可以使用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引擎自动执行。