JSON: Difference between revisions

309 bytes removed ,  9 years ago
→‎{{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 {
return [appendjson::write resultstring "}"$value]
# Skip to the mapping code at the bottom
}
dict {
setreturn result[json::write object "{"*}[
dict formap {k v} $value {tcl2json $v}]]
set pfx ""
dict for {k v} $value {
append result $pfx [tcl2json $k] ": " [tcl2json $v]
set pfx ", "
}
return [append result "}"]
}
list {
return [json::write array {*}[lmap v $value {tcl2json $v}]]
set result "\["
set pfx ""
foreach v $value {
append result $pfx [tcl2json $v]
set pfx ", "
}
return [append result "\]"]
}
int - double {
Line 2,556 ⟶ 2,547:
return [expr {$value ? "true" : "false"}]
}
return [appendjson::write resultstring "\]"$value]
}
}
 
# For simplicity, all "bad" characters are mapped to \u... substitutions
set mapped [subst -novariables [regsub -all {[][\u0000-\u001f\\""]} \
$value {[format "\\\\u%04x" [scan {& } %c]]}]]
return "\"$mapped\""
}</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>{"blue": [1, 2], "ocean" : "water"}</pre>
}
</pre>
Note that this is capable of correctly handling the round-trip of values parsed from the <code>json</code> package described above.
 
Anonymous user