Anonymous user
JSON: Difference between revisions
→{{header|Tcl}}: Improved version using new tcllib package
(→{{header|Tcl}}: Improved version using new tcllib package) |
|||
Line 2,508:
<br>
{{works with|Tcl|8.6}}
{tcllib|json::write}}
<lang tcl>package require Tcl 8.6
package require json::write
proc tcl2json value {
Line 2,517 ⟶ 2,519:
switch $type {
string {
}
dict {
▲ dict for {k v} $value {
▲ return [append result "}"]
}
list {
return [json::write array {*}[lmap v $value {tcl2json $v}]]
return [append result "\]"]▼
}
int - double {
Line 2,556 ⟶ 2,547:
return [expr {$value ? "true" : "false"}]
}
}
}
}</lang>
Sample code (note that the value is built with <code>dict create</code> and <code>list</code> so that there is some auxiliary type hints available, which the above procedure can read):
Line 2,568 ⟶ 2,555:
puts [tcl2json $d]</lang>
{{out}}
<pre>
<pre>{"blue": [1, 2], "ocean": "water"}</pre>▼
{
"blue" : [1,2],
}
</pre>
Note that this is capable of correctly handling the round-trip of values parsed from the <code>json</code> package described above.
|