首页 > 解决方案 > Tcl 列表和 Json

问题描述

我第一次在 tcl 中处理 json 包,我正在尝试将列表列表转换为 json 格式。下面的代码给了我需要的结果,但我想知道是否有更简单的方法,或者下面的代码是否存在任何潜在问题。(在我的应用程序中,一切都是字符串)

package require json
package require json::write

set countryList [list [list {USA} {Washington DC}] [list {India} {New Delhi}] [list {Greece} {Athens}]]

set myList [list]
foreach country $countryList {
    lappend myList [lindex $country 0]
    lappend myList [json::write string [lindex $country 1]]
}

set nodeName "capitals"
set jsonStr [json::write object $nodeName [json::write object {*}$myList]]
puts $jsonStr

#{
#    "capitals" : {
#   "USA"    : "Washington DC",
#   "India"  : "New Delhi",
#   "Greece" : "Athens"
#    }
#}

标签: jsontcl

解决方案


使用dict代替列表可以使它更干净:

#!/usr/bin/env tclsh
package require json
package require json::write

set countryDict [dict create \
                     USA {Washington DC} \
                     India {New Delhi} \
                     Greece Athens]
set myDict [dict map {country capital} $countryDict {
    set capital [json::write string $capital]
}]

set nodeName capitals
set jsonStr [json::write object $nodeName [json::write object {*}$myDict]]
puts $jsonStr

或者,foreach支持在每次迭代中处理列表的多个元素(并且lappend可以通过一次调用添加多个元素):

set countryList [list \
                     USA {Washington DC} \
                     India {New Delhi} \
                     Greece Athens]
foreach {country capital} $countryList {
    lappend myList $country [json::write string $capital]
}

推荐阅读