我是TCL的新手,我有一个JSON字符串,我想把它解析为一些我可以轻松使用的东西,就像在Perl或Java中类似的哈希/数组来循环数据并打印它。但是我找到了许多帮助我的消息来源,但它却很少,但仍然无法得到它。
我尝试这样的事情:
#!/usr/bin/tclsh
proc dict2json {dictVal} {
# XXX: Currently this API isn't symmetrical, as to create proper
# XXX: JSON text requires type knowledge of the input data
set json ""
dict for {key val} $dictVal {
# key must always be a string, val may be a number, string or
# bare word (true|false|null)
if {0 && ![string is double -strict $val]
&& ![regexp {^(?:true|false|null)$} $val]} {
set val "\"$val\""
}
append json "\"$key\": $val," \n
}
return "\{${json}\}"
}
set json {{"Object1":{"Year":"2012","Quarter":"Q3","DataType":"Other 3","Environment":"STEVE","Amount":125},"Object2":{"Year":"2012","Quarter":"Q4","DataType":"Other 2","Environment":"MIKE","Amount":500}}}
puts [dict2json $json]
我从其他来源获得的代码,但它返回我的错误,我几乎生气这个,任何人都可以帮助?谢谢。
答案 0 :(得分:2)
最明智的方法是使用现有代码:
% package require json
1.3.3
% set json {{"Object1":{"Year":"2012","Quarter":"Q3","DataType":"Other 3","Environment":"STEVE","Amount":125},"Object2":{"Year":"2012","Quarter":"Q4","DataType":"Other 2","Environment":"MIKE","Amount":500}}}
{"Object1":{"Year":"2012","Quarter":"Q3","DataType":"Other 3","Environment":"STEVE","Amount":125},"Object2":{"Year":"2012","Quarter":"Q4","DataType":"Other 2","Environment":"MIKE","Amount":500}}
% ::json::json2dict $json
Object1 {Year 2012 Quarter Q3 DataType {Other 3} Environment STEVE Amount 125} Object2 {Year 2012 Quarter Q4 DataType {Other 2} Environment MIKE Amount 500}
json
软件包未与ActiveTcl捆绑在一起,但可以与teacup install json
一起安装,或者通过获取文件json.tcl
和json_tcl.tcl
来安装,如果有的话Tcl 8.5或更高版本,以及pkgIndex.tcl
。将这些文件放在Tcl找到它们的地方(puts $auto_path
会给你一个地方列表)。
文档: json (package), package, set