2016-12-08 2 views
0

저는 TCL에서 새롭고 JSON 문자열이 있는데이를 펄이나 자바에서와 비슷한 비슷한 해시/배열과 같은 방식으로 쉽게 사용할 수있는 구문으로 파싱하려고합니다. 데이터를 인쇄하고 인쇄하십시오. 그러나 나는 많은 도움을 얻을 수있는 근원을 찾았지만, 그 수가 적고 여전히 얻을 수 없습니다.TCL - 해시/배열로 JSON 구문 분석

그리고이 같은 시도 :

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

코드 나 다른 소스에서 얻을 수 있지만, 그것은 나에게 오류를 반환, 내가 거의 이것에 미친 사람이 도움이 될 수 있습니다받을를? 고맙습니다.

+2

당신이 tcllib에서 JSON 패키지를 시도 package, json (package)? 원하는대로해야하는 json2dict 명령이 있습니다. –

답변

1

가장 합리적인 방법은 기존 코드를 사용하는 것입니다

json 패키지는 ActiveTcl 함께 번들로 제공되지 않지만 경우` teacup install json 설치하거나 파일 json.tcljson_tcl.tcl을,`얻어서 할 수
% 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} 

Tcl 8.5 이상 및 pkgIndex.tcl이 있습니다. 이 파일들을 Tcl이 찾을 수있는 어딘가에 넣으십시오 (puts $auto_path는 장소 목록을 제공합니다).

문서 : set