tcl json解析:如何处理数组

时间:2016-03-14 18:56:21

标签: json tcl

我试图简单地用TCL解析一个json。我用json2dict解析后如何处理json中的数组并不明显。

这是我的代码:

package require json

set jsonStr { 
  { "photos": { "page": 1, "pages": "726", "perpage": 3, "total": "7257", 
    "photo": [
      { "id": "6974156079", "owner": "74957296@N08", "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": "52857411@N08", "secret": "56630c18e8", "server": "7183", "farm": 8, "title": "Gedi Ruins, Local Guide", "ispublic": 1, "isfriend": 0, "isfamily": 0 },
      { "id": "6822909640", "owner": "52857411@N08", "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

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

由于

2 个答案:

答案 0 :(得分:0)

foreach photo $photos {puts $photo}

为你工作?

答案 1 :(得分:0)

因为返回的数据是字典,我发现了一个字典代码修复:

package require json

set jsonStr { 
  { 
    "photos": { "page": 1, "pages": "726", "perpage": 3, "total": "7257", 
    "photo": [
          { "id": "6974156079", "owner": "74957296@N08", "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": "52857411@N08", "secret": "56630c18e8", "server": "7183", "farm": 8, "title": "Gedi Ruins, Local Guide", "ispublic": 1, "isfriend": 0, "isfamily": 0 },
          { "id": "6822909640", "owner": "52857411@N08", "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"
        }
      }
  }
}