2016-03-14 103 views
0

我想简单解析一个json与TCL。在使用json2dict解析后,如何在json中处理数组并不明显。tcl json解析:如何处理数组

这里是我的代码:

package require json 

set jsonStr { 
    { "photos": { "page": 1, "pages": "726", "perpage": 3, "total": "7257", 
    "photo": [ 
     { "id": "6974156079", "owner": "[email protected]", "secret": "005d743f82", "server": "7197", "farm": 8, "title": "Kenya Watamu \"Deep Sea Fishing\" \"Indian Ocean\" \"Blue Marlin\"", "ispublic": 1, "isfriend": 0, "isfamily": 0 }, 
     { "id": "6822988100", "owner": "[email protected]", "secret": "56630c18e8", "server": "7183", "farm": 8, "title": "Gedi Ruins, Local Guide", "ispublic": 1, "isfriend": 0, "isfamily": 0 }, 
     { "id": "6822909640", "owner": "[email protected]", "secret": "f4e392ea36", "server": "7063", "farm": 8, "title": "Local Fisherman, Mida Creek", "ispublic": 1, "isfriend": 0, "isfamily": 0 } 
    ] }, "stat": "ok" } 
} 

set d1 [json::json2dict $jsonStr] 
foreach key [dict keys $d1] val [dict values $d1] { 
    puts "The value associated with $key is $val" 
} 

puts "list of photos:" 
set photos [ dict get $d1 photos photo ] 
puts $photos 

而且我希望能够遍历的,我在代码末尾显示照片列表。

感谢

回答

0

由于返回的数据是一个字典我发现字典码的修正:

package require json 

set jsonStr { 
    { 
    "photos": { "page": 1, "pages": "726", "perpage": 3, "total": "7257", 
    "photo": [ 
      { "id": "6974156079", "owner": "[email protected]", "secret": "005d743f82", "server": "7197", "farm": 8, "title": "Kenya Watamu \"Deep Sea Fishing\" \"Indian Ocean\" \"Blue Marlin\"", "ispublic": 1, "isfriend": 0, "isfamily": 0 }, 
      { "id": "6822988100", "owner": "[email protected]", "secret": "56630c18e8", "server": "7183", "farm": 8, "title": "Gedi Ruins, Local Guide", "ispublic": 1, "isfriend": 0, "isfamily": 0 }, 
      { "id": "6822909640", "owner": "[email protected]", "secret": "f4e392ea36", "server": "7063", "farm": 8, "title": "Local Fisherman, Mida Creek", "ispublic": 1, "isfriend": 0, "isfamily": 0 } 
     ] }, 
    "stat": "ok" 
    } 
} 

set d1 [json::json2dict $jsonStr] 
puts $d1 

foreach key [dict keys $d1] val [dict values $d1] { 
    puts "$key:" 
    puts "==> $val" 
    if { $key == "photos" } { 
     dict for {k1 v1} $val { 
     if {$k1 == "photo"} { 
      puts "iterating over photos" 
      puts $v1 
      set i 0 
      foreach photo $v1 { 
       incr i 
       puts "$i: $photo" 
       dict for {k2 v2} $photo { 
        puts "\t\t$k2: $v2" 
       }    
      }   

     } else { 
      puts "\t$k1: $v1" 
     } 
     } 
    } 
} 
0

是不是

foreach photo $photos {puts $photo} 

为你工作?