json tcl_确定TCL中变量的类型
Tcl的變量沒(méi)有類(lèi)型(除了他們是否真的變量的關(guān)聯(lián)數(shù)組 - 即使用$foo(bar)語(yǔ)法 - FO r你使用array exists)但Tcl的值。好吧,有點(diǎn)。 Tcl可以在不同類(lèi)型之間進(jìn)行變異,因?yàn)樗J(rèn)為合適,并且不公開(kāi)這些信息[*];你所能做的就是檢查一個(gè)值是否符合特定的類(lèi)型。
這種一致性檢查與完成string is(在您需要的-strict選項(xiàng),丑陋的歷史原因):
if {[string is integer -strict $foo]} {
puts "$foo is an integer!"
}
if {[string is list $foo]} { # Only [string is] where -strict has no effect
puts "$foo is a list! (length: [llength $foo])"
if {[llength $foo]&1 == 0} {
# All dictionaries conform to lists with even length
puts "$foo is a dictionary! (entries: [dict size $foo])"
}
}
請(qǐng)注意,所有值符合字符串類(lèi)型; Tcl的值是總是可序列化。對(duì)于JSON序列化,可以使用骯臟的黑客來(lái)產(chǎn)生一個(gè)“正確的”序列化(嚴(yán)格地說(shuō),從Tcl的角度來(lái)看,所有東西都是正確的,但這對(duì)其他語(yǔ)言并不完全有幫助)與Tcl 8.6。代碼要做到這一點(diǎn),原本張貼在Rosetta Code是:
package require Tcl 8.6
proc tcl2json value {
# Guess the type of the value; deep *UNSUPPORTED* magic!
regexp {^value is a (.*?) with a refcount} \
[::tcl::unsupported::representation $value] -> type
switch $type {
string {
# Skip to the mapping code at the bottom
}
dict {
set result "{"
set pfx ""
dict for {k v} $value {
append result $pfx [tcl2json $k] ": " [tcl2json $v]
set pfx ", "
}
return [append result "}"]
}
list {
set result "\["
set pfx ""
foreach v $value {
append result $pfx [tcl2json $v]
set pfx ", "
}
return [append result "\]"]
}
int - double {
return [expr {$value}]
}
booleanString {
return [expr {$value ? "true" : "false"}]
}
default {
# Some other type; do some guessing...
if {$value eq "null"} {
# Tcl has *no* null value at all; empty strings are semantically
# different and absent variables aren't values. So cheat!
return $value
} elseif {[string is integer -strict $value]} {
return [expr {$value}]
} elseif {[string is double -strict $value]} {
return [expr {$value}]
} elseif {[string is boolean -strict $value]} {
return [expr {$value ? "true" : "false"}]
}
}
}
# 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\""
}
警告:不支持上面的代碼。這取決于骯臟的黑客。它很容易在沒(méi)有預(yù)警的情況下突破。 (但是它不工作。移植到Tcl的8.5將需要一個(gè)微小的C擴(kuò)展到讀出的類(lèi)型的注釋。)
[*]嚴(yán)格,但它用于發(fā)現(xiàn)當(dāng)前類(lèi)型注釋提供一個(gè)不支持的接口的價(jià)值為8.6 - 作為::tcl::unsupported::representation的一部分 - 但該信息采用刻意的人類(lèi)可讀形式,如有更改,恕不另行通知。它用于調(diào)試,而不是代碼。而且,Tcl在內(nèi)部使用相當(dāng)多的不同類(lèi)型(例如,,緩存的命令和變量名稱(chēng)),在正常情況下你不想探測(cè);事情是引擎蓋下相當(dāng)復(fù)雜的...
總結(jié)
以上是生活随笔為你收集整理的json tcl_确定TCL中变量的类型的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Kotlin AAPT: error:
- 下一篇: Gensee Android SDK(