JSON and Huddle

JSON 数据格式在 Web 开发中常用于传递数据到前端页面。

JSON

{
  a: 1
  b: "hello"
  c: [4, 5, 6]
}

Huddle

  • Huddle - https://core.tcl-lang.org/tcllib
HUDDLE {
  D {
    a {num 1}
    b {s "hello}
    c {L {4 5 6}}
  }
}
  • D - dict
  • L - list
  • s - string
  • num - Number
  • b - Boolean
  • null - null

就本质来说,Huddle 格式是由 [list $tag $data] 递归定义。最顶层节点的 tag 是 HUDDLE

compile_json

# data is plain old tcl values
# spec is defined as follows:
# {string} - data is simply a string, "quote" it if it's not a number
# {list} - data is a tcl list of strings, convert to JSON arrays
# {list list} - data is a tcl list of lists
# {list dict} - data is a tcl list of dicts
# {dict} - data is a tcl dict of strings
# {dict xx list} - data is a tcl dict where the value of key xx is a tcl list
# {dict * list} - data is a tcl dict of lists
# etc..
proc compile_json {spec data} {
    while [llength $spec] {
        set type [lindex $spec 0]
        set spec [lrange $spec 1 end]
        
        switch -- $type {
            dict {
                lappend spec * string
                
                set json {}
                foreach {key val} $data {
                    foreach {keymatch valtype} $spec {
                        if {[string match $keymatch $key]} {
                            lappend json [subst {"$key":[
                                compile_json $valtype $val]}]
                            break
                        }
                    }
                }
                return "{[join $json ,]}"
            }
            list {
                if {![llength $spec]} {
                    set spec string
                } else {
                    set spec [lindex $spec 0]
                }
                set json {}
                foreach {val} $data {
                    lappend json [compile_json $spec $val]
                }
                return "\[[join $json ,]\]"
            }
            string {
                if {[string is double -strict $data]} {
                    return $data
                } else {
                    return "\"$data\""
                }
            }
            default {error "Invalid type"}
        }
    }
}

常见的数据结构:

  • compile_json {list dict} $data - list of dict
  • compile_json {list list} $data - list of list
  • compile_json {dict * list} $data - dict of list