TCL-将JSON解析为哈希/数组 [英] TCL - Parse JSON to hash/array

查看:257
本文介绍了TCL-将JSON解析为哈希/数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是TCL的新手,我有一个JSON字符串,我想将其解析为某种我可以轻松使用的东西,例如hash/array,类似于Perl或Java中的数据循环和打印.但是我找到了很多资源可以帮助我,但是数量很少,但仍然无法获得.

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.

我尝试这样的事情:

#!/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.

推荐答案

最明智的方法是使用现有代码:

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}

json软件包未与ActiveTcl捆绑在一起,但可以与teacup install json一起安装,也可以通过获取文件json.tcljson_tcl.tcl进行安装,``"(如果您具有Tcl 8.5或更高版本,并且.将这些文件放在Tcl可以找到它们的位置(puts $auto_path将为您提供位置列表).

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).

文档: json(包)程序包集合

这篇关于TCL-将JSON解析为哈希/数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆