0

please assist me in this ,,,

I have a tcl array called all_tags ,, but the thing is i need to convert it into a javascript array in my page but i am weak when it comes to javascript .

please advise me if below is correct and if not ,,what is the right way ?

<script>
var mytags = new Array();
<% 
foreach tag $all_tags {
     ns_puts [subst {
         mytags.push('$tag');
         }]
}
%>
</script>

and afterwards is it possible to use my javascript array in a tcl proc ?

4

1 回答 1

2

要将 Tcl 中的数据转换为 JSON,您需要json::write来自 Tcllib 的包。您可以像这样使用它从 Tcl 数组创建 JSON 对象(类似的方法适用于 Tcl 字典):

package require json::write

set accumulate {}
foreach {key value} [array get yourArray] {
    lappend accumulate $key [json::write string $value]
}
set theJsonObject [json::write object {*}$accumulate]

要将 Tcl 列表转换为 JSON 数组:

package require json::write
set accumulate {}
foreach item $yourList {
    lappend accumulate [json::write string $value]
}
set theJsonArray [json::write array {*}$accumulate]

请注意,在这两种情况下,我假设这些值都将表示为 JSON 字符串。如果要嵌入的值是数字(或truefalse),您不需要做任何特别的事情;Tcl 看到的值就像 JSON 文字一样工作得很好。嵌入列表/数组/字典需要“递归”使用json::write和更多的计划——这不是自动的,因为 Tcl 和 JSON 有非常不同的类型概念。

于 2013-06-25T19:35:20.140 回答