Tcl Library Source Code

View Ticket
Login
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: Open Last Modified: 2013-04-11 10:01:23
Resolution: None Closed By:
    Closed on:
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"}}}