I would like to parse a varialbe name into a JSON string:
JSON:
{
"items": [
{
"id": "2000",
"butt开发者_开发百科ons": [{
"text": systemvar.continue,
}]
}
}
systemvar.continue is defined in Javascript.
How do I write the JSON code to use the Javascript variable?
Any ideas?
Best Kurt
If systemvar.continue
is defined in JavaScript, then make your JSON valid like this:
{
"items": [
{
"id": "2000",
"buttons": [{
"text": "continue", // <-- only pass the property name
}]
}
}
And then access the "continue"
property of systemvar
using square bracket notation.
var result = systemvar[ json.items[0].buttons[0].text ];
Of course this is hardcoded and assumes your parsed JSON is referenced in a variable called json
. I assume you're traversing the structure, and will come across text:"continue"
at some point. When you get there, plug it in as the property name.
// in traversal
systemvar[ val.text ];
I'd also suggest that you avoid the word continue
since it's a reserved word, though it will work with a string in square brackets.
JSON is a safe, restricted subset of JavaScript's syntax. If you want to allow any JavaScript syntax, including that which is potentially unsafe, use eval()
instead of JSON.parse()
.
I think what you can use is JSONP.
The client-side would have this html code:
<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>
And the server would return:
readData(
{
"items": [
{
"id": "2000",
"buttons": [{
"text": systemvar.continue,
}]
}
}
)
Note that this means that your returned "JSON array" is automatically executed by the browser's javascript engine.
精彩评论