TCL - Parse JSON to hash/array

帅比萌擦擦* 提交于 2021-02-16 15:36:06

问题


I'm new in TCL, I have an JSON string, and I want to parse it to something I can use it easily like hash/ array which similar like in Perl or Java to loop the data and print it. But I've found many sources to help me, but it is very less and still couldn't get it.

And I try something like this:

#!/usr/bin/tclsh
proc dict2json {dictVal} {
    # XXX: Currently this API isn't symmetrical, as to create proper
    # XXX: JSON text requires type knowledge of the input data
    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)
    if {0 && ![string is double -strict $val]
        && ![regexp {^(?:true|false|null)$} $val]} {
        set val "\"$val\""
    }
        append json "\"$key\": $val," \n
    }

    return "\{${json}\}"
}

set json {{"Object1":{"Year":"2012","Quarter":"Q3","DataType":"Other 3","Environment":"STEVE","Amount":125},"Object2":{"Year":"2012","Quarter":"Q4","DataType":"Other 2","Environment":"MIKE","Amount":500}}}

puts [dict2json $json]

The code I get from other sources, but it return me error, I almost get mad on this, anyone can help? Thank you.


回答1:


The most sensible way is to use existing code:

% package require json
1.3.3

% set json {{"Object1":{"Year":"2012","Quarter":"Q3","DataType":"Other 3","Environment":"STEVE","Amount":125},"Object2":{"Year":"2012","Quarter":"Q4","DataType":"Other 2","Environment":"MIKE","Amount":500}}}
{"Object1":{"Year":"2012","Quarter":"Q3","DataType":"Other 3","Environment":"STEVE","Amount":125},"Object2":{"Year":"2012","Quarter":"Q4","DataType":"Other 2","Environment":"MIKE","Amount":500}}

% ::json::json2dict $json
Object1 {Year 2012 Quarter Q3 DataType {Other 3} Environment STEVE Amount 125} Object2 {Year 2012 Quarter Q4 DataType {Other 2} Environment MIKE Amount 500}

The json package isn't bundled with ActiveTcl, but can be installed with teacup install json, or by getting the files json.tcl and json_tcl.tcl, `` if you have Tcl 8.5 or later, and pkgIndex.tcl. Put those files somewhere where Tcl will find them (puts $auto_path will give you a list of places).

Documentation: json (package), package, set



来源:https://stackoverflow.com/questions/41034670/tcl-parse-json-to-hash-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!