json - 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"
# }
#}
解决方案
使用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]
}
推荐阅读
- jquery - reactjs状态变化时如何正确更新jquery数据表内容?
- java - org.springframework.beans.factory.BeanCreationException:创建工厂bean时出错
- solidity - Metamask 自定义 RPC 未发送正确的合约信息
- android - Android - 毕加索获取图像高度
- python - 如何更改网页代码打开的目录TCP服务器python
- html - 如何使 firstChild 高度为 100% flexbox 包装项目
- firebase - Firebase 不会更新我对自定义域的更改
- mongodb - Mongodb Compass和shell中的mongodb查找聚合结果不同
- r - Taking values from data table rows and putting it in a cell as a list in R
- c# - 通过 RestSharp C# 将 JSON 数组发布到 PHP API