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 ?

2
  • Is it an array or a list? Tcl arrays are more like JS objects than JS arrays (which are in turn more like Tcl lists). Commented Jun 25, 2013 at 12:27
  • well it was a tcl array but now I have turned it into a tcl list of {{key value} {key value} ....} ,,and I need to turn it into javascript array of key and value ,, can you help me with that please ? Commented Jun 25, 2013 at 12:50

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

If you've got something specific you want to achieve, do ask another question with more detail so that it will guide us better to a helpful answer.
thanks a lot ! yes it turned into a json list :) I wanted to use it to keep changing the content of a select list based on the change that happens in the tcl array :D Many thanks @Donal Fellows

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.