On Thu, 29 May 2014 14:25:11 -0700, patna73 wrote:
> Hello, has anyone written any snippets to convert from keyed list to
> JSON? I tried to use the JSON::dict2json and browsing at the code, it
> may not work well.
I'm surprised that you came across dict2json as it isn't documented. It
doesn't work in any case because JSON needs to know the type of data you
are working with. What you really need to do is create a custom proc to
convert a dict to JSON when you know how it is formatted. As so:
package require json
package require json::write
proc qualifications2Json {qualifications} {
set res {}
foreach qualification $qualifications {
lappend res [json::write string $qualification]
}
json::write array {*}$res
}
proc employeeDict2Json {employeeDict} {
set name [json::write string [dict get $employeeDict name]]
set age [dict get $employeeDict age]
set qualifications \
[qualifications2Json [dict get $employeeDict qualifications]]
json::write object name $name age $age qualifications $qualifications
}
set employeeJson {
{ "name": "Fred Smith",
"age": 28,
"qualifications": ["BSc", "MSc", "Phd"] }}
set employeeDict [::json::json2dict $employeeJson]
puts "employeeJson: $employeeJson\n"
puts "employeeDict: $employeeDict\n\n"
puts "dict2json fails as it doesn't quote the name, nor create a proper \
array for qualifications"
puts "dict2json: [::json::dict2json $employeeDict]\n"
puts "employeeDict2Json: [employeeDict2Json $employeeDict]\n"
puts "employeeDict2Json -> json2Dict: \
[::json::json2dict [employeeDict2Json $employeeDict]]\n"
That will produce the following output:
employeeJson:
{ "name": "Fred Smith",
"age": 28,
"qualifications": ["BSc", "MSc", "Phd"] }
employeeDict: name {Fred Smith} age 28 qualifications {BSc MSc Phd}
dict2json fails as it doesn't quote the name, nor create a proper array
for qualifications
dict2json: {"name": Fred Smith,
"age": 28,
"qualifications": BSc MSc Phd,
}
employeeDict2Json: {
"name" : "Fred Smith",
"age" : 28,
"qualifications" : ["BSc","MSc","Phd"]
}
employeeDict2Json -> json2Dict: name {Fred Smith} age 28 qualifications
{BSc MSc Phd}
This isn't in the best style as I haven't done any Tcl for about six
months so I'm a bit rusty, but I hope that it helps.
Lorry
--
vLife Systems Ltd
Registered Office: The Apex, 2 Sheriffs Orchard, Coventry, CV1 3PP
Registered in England and Wales No. 06477649
http://vlifesystems.com