如何在 tcl 中进行 JSON 编组?

How to do JSON marshalling in tcl?

我正在尝试为我们的一个要求创建一个 JSON,我想在我的 Tcl 脚本中进行 JSON 编组,有什么方法可以在 Tcl 中做同样的事情。任何带有示例的解决方案都会更有用。

推荐使用 Tcllib 中的 json::write 包,但它非常原始。

package require json::write

set abc {This is an example with "quotes" in it}
set pqr "yet another string"
set stu "and another"
puts [json::write object abc [json::write string $abc] def [
    json::write array \
       123 \
       [json::write string $pqr] \
       [json::write string $stu]
]]

当我尝试时会产生这个输出:

{
    "abc" : "This is an example with \"quotes\" in it",
    "def" : [123,"yet another string","and another"]
}

您还可以使用 Rosetta Code 中描述的(邪恶的,类型感知的)技术;它建立在 json::write 包之上(现在我已经重写了它......)并让你做:

puts [tcl2json [dict create "abc" $abc "def" [list 123 $pqr $stu]]]

生成相同的输出。