tcladp

how to create javascript array from tcl array


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 ?


Solution

  • To turn data in Tcl into JSON, you want the json::write package from Tcllib. You'd use it like this to make a JSON object from a Tcl array (and a similar approach works for Tcl dictionaries):

    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]
    

    To turn a Tcl list into a JSON array:

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

    Note in these two cases I've assumed that the values are all to be represented as JSON strings. If the values to embed are numbers (or true or false) you don't need to do anything special; the values as Tcl sees them work just fine as JSON literals. Embedding lists/arrays/dicts takes “recursive” use of json::write and a bit more planning — it's not automatic as Tcl and JSON have really very different concepts of types.