将元素添加到TCL中字典中的数组

时间:2015-01-08 12:49:08

标签: arrays dictionary tcl

我想在字典中向数组(列表?)中添加一个元素,并且无法解决问题。

我是从json对象创建一个dict,看起来大致如下:

{"channel1":{"badwords":["test", "demo"]}, "channel2":{"badwords":["remove"]}}

这个JSON被转换为dict,我可以访问坏词

[dict get $channels "channel1" "badwords"]

我需要通过为它添加新值来更新dict,基本上将其设为:

{"channel1":{"badwords":["test", "demo", "new"]}, "channel2":{"badwords":["remove"]}}

1 个答案:

答案 0 :(得分:1)

我发现字典有点棘手。依靠文档:http://tcl.tk/man/tcl8.6/TclCmd/dict.htm

set json {{"channel1":{"badwords":["test", "demo"]}, "channel2":{"badwords":["remove"]}}}
package require json  # from tcllib

set channels [json::json2dict $json]
# ==> channel1 {badwords {test demo}} channel2 {badwords remove}

dict update channels channel1 subdict1 {dict lappend subdict1 badwords "new"}
# or, "dict with" that sets local variables you can manipulate
dict with channels channel1 {lappend badwords "new"}

set channels
# ==> channel1 {badwords {test demo new}} channel2 {badwords remove}
相关问题