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.