问题
I'm new in TCL, I have an JSON string, and I want to parse it to something I can use it easily like hash/ array which similar like in Perl or Java to loop the data and print it. But I've found many sources to help me, but it is very less and still couldn't get it.
And I try something like this:
#!/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]
The code I get from other sources, but it return me error, I almost get mad on this, anyone can help? Thank you.
回答1:
The most sensible way is to use existing code:
% 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}
The json
package isn't bundled with ActiveTcl, but can be installed with teacup install json
, or by getting the files json.tcl
and json_tcl.tcl
, `` if you have Tcl 8.5 or later, and pkgIndex.tcl
. Put those files somewhere where Tcl will find them (puts $auto_path
will give you a list of places).
Documentation: json (package), package, set
来源:https://stackoverflow.com/questions/41034670/tcl-parse-json-to-hash-array