Suresh
Suresh

Reputation: 119

Tcl List and Json

I am dealing with json package in tcl for the first time and I am trying to convert a list of list into json format. Below code is giving me the results I need, but I wonder if there is any easier way or if there is any potential issues with the code below. (In my application everything is string)

package require json
package require json::write

set countryList [list [list {USA} {Washington DC}] [list {India} {New Delhi}] [list {Greece} {Athens}]]

set myList [list]
foreach country $countryList {
    lappend myList [lindex $country 0]
    lappend myList [json::write string [lindex $country 1]]
}

set nodeName "capitals"
set jsonStr [json::write object $nodeName [json::write object {*}$myList]]
puts $jsonStr

#{
#    "capitals" : {
#   "USA"    : "Washington DC",
#   "India"  : "New Delhi",
#   "Greece" : "Athens"
#    }
#}

Upvotes: 2

Views: 617

Answers (2)

glenn jackman
glenn jackman

Reputation: 246847

With the RubyLane rl_json package, we can do:

set countryDict [dict create {*}{
    USA     "Washington DC"
    India   "New Delhi"
    Greece  Athens
}]

package req rl_json
namespace import rl_json::json

dict for {country capital} $countryDict {
    json set obj $country $capital
}

puts $obj
puts [json pretty $obj]

outputs

{"USA":"Washington DC","India":"New Delhi","Greece":"Athens"}
{
    "USA":    "Washington DC",
    "India":  "New Delhi",
    "Greece": "Athens"
}

With the huddle package from tcllib

package require huddle
set h [huddle create {*}$countryDict]
set json [huddle jsondump $h]

Upvotes: 2

Shawn
Shawn

Reputation: 52439

Using dicts instead of lists can make it cleaner:

#!/usr/bin/env tclsh
package require json
package require json::write

set countryDict [dict create \
                     USA {Washington DC} \
                     India {New Delhi} \
                     Greece Athens]
set myDict [dict map {country capital} $countryDict {
    set capital [json::write string $capital]
}]

set nodeName capitals
set jsonStr [json::write object $nodeName [json::write object {*}$myDict]]
puts $jsonStr

Alternatively, foreach supports handling multiple elements of a list in each iteration (And lappend can add multiple elements with a single call):

set countryList [list \
                     USA {Washington DC} \
                     India {New Delhi} \
                     Greece Athens]
foreach {country capital} $countryList {
    lappend myList $country [json::write string $capital]
}

Upvotes: 2

Related Questions