| Ticket UUID: | 3610482 | |||
| Title: | Symmetrical json conversion | |||
| Type: | Patch | Version: | None | |
| Submitter: | tombert | Created on: | 2013-04-10 18:11:03 | |
| Subsystem: | json | Assigned To: | andreas_kupries | |
| Priority: | 5 Medium | Severity: | ||
| Status: | Closed | Last Modified: | 2026-11-21 10:33:57 | |
| Resolution: | Out of Date | Closed By: | serhiy.storchaka | |
| Closed on: | 2026-11-21 10:33:57 | |||
| Description: |
I propose the following enhancement:
proc json::dict2json {dictVal {keys {}}} {
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) or a dict if provided in keys
## check if we can resolve the value to a dictionary
if {($key in $keys) && ![catch {dict keys $val}]} {
set val [json::dict2json $val $keys]
} elseif {![string is double -strict $val]
&& ![regexp {^(?:true|false|null)$} $val]} {
set val "\"$val\""
}
if {$json ne ""} {append json ","}
append json "\"$key\":$val"
}
return "\{${json}\}"
}
Normally one knows the keys in a dictionary, how else would you be able to access them? Thus you could also pass a list of all possible keys allowing for symmetric conversion:
> json::json2dict {{"user1":{"maint":"yes"},"user2":{"maint":"no","home":{"town":"Vienna","state":"Austria"}}}}
user1 {maint yes} user2 {maint no home {town Vienna state Austria}}
> json::dict2json {user1 {maint yes} user2 {maint no home {town Vienna state Austria}}} {user1 user2 home}
{"user1":{"maint":"yes"},"user2":{"maint":"no","home":{"town":"Vienna","state":"Austria"}}}
| |||
| User Comments: |
serhiy.storchaka added on 2026-11-21 10:33:57:
JSON with explicit types is generated with json::write ([6a47bc5353], Tcllib 1.12) or huddle. A key list cannot make the conversion symmetric in general (strings, numbers and nested values look alike in a dict). | |||
Home
Blog
Docs
Downloads
Tickets
Timeline
Branches
Tags
Wiki