tcvJSON Parser

1 Introduction

tcvJSON is derived from the json module found in tcllib. The fundamental problem with tcllib is while it does a great job at parsing JSON data, it does so in a way that does not maintain the JSON structure unambiguously in Tcl. That is, going from JSON to Tcl and back to JSON is not possible. tcvJSON was written as an enhanced version of the json module in tcllib to address these issues.

This it does by tagging each ambiguous part of a JSON structure with a type. There is a type for numbers, strings, arrays, and objects. The bare words “true,” “false,” and “null” retain their meaning without tags. Everything else is qualified with some kind of tag indicating its types. This allows us to unambiguously convert JSON to Tcl, manipulate the result with Tcl commands, and finally convert back to JSON while maintaining the original structure, plus any intended structure added while it was in the Tcl representation.

2 Commands

— Command: tcvJSON::create type
— Command: tcvJSON::add! [-type type] jsonName thing

Appends thing onto the end of the JSON list stored in jsonName. Signals an error if the value of jsonName is not a JSON array.

— Command: tcvJSON::put! [-type type] jsonName key value

Adds the key/value pair given to the JSON object stored in jsonName. Signals an error if the value of jsonName is not a JSON object.

— Command: tcvJSON::unparse json

Return the JSON form of the value json as a string.

— Command: tcvJSON::write [channel] jsonName

Writes the JSON representation of the data stored in jsonName out on channel (or stdout if not provided).

— Command: tcvJSON::parse txt

Parse the text stored in txt and return a Tcl representation of that JSON data.

— Command: tcvJSON::objForEach k v obj script

For each key/value pair in obj, evaluates script with variables named k and v set to the current key and value, respectively.

     
          ::tcvJSON::objForEach key value $jsonObject {
              puts "$key => $value"
          }
     
— Command: tcvJSON::exists? json thing
— Command: tcvJSON::listForEach e lst script

For each element in lst, evaluates script with the variable named e set to the current element.

     
          set i 0
          ::tcvJSON::listForEach elt $jsonArray {
              puts "[$i] $elt"
              incr i
          }