Avi
Avi

Reputation: 318

TCL to JSON : Writing JSON output using huddle in single line

Let us consider a tcl data as follows:

set arr {a {{c 1} {d {2 2 2} e 3}} b {{f 4 g 5}}}

Converted into Json format using huddle module:

set json_arr [huddle jsondump [huddle compile {dict * {list {dict d list}}} $arr]]
puts $json_arr

Json fromatted array:

{
  "a": [
    {"c": 1},
    {
      "d": [
        2,
        2,
        2
      ],
      "e": 3
    }
  ],
  "b": [{
      "f": 4,
      "g": 5
    }]
}

Writing in a single line:

set json_arr [huddle jsondump [huddle compile {dict * {list {dict d list}}} $arr] {} {}]
puts $json_arr

Updated Json formatted array:

{"a":[{"c":1},{"d":[2,2,2],"e":3}],"b":[{"f":4,"g":5}]}

What is the meaning of {} {} here?

Can I use the same for single line in case of output by json and json::write module ?

Upvotes: 0

Views: 540

Answers (1)

Peter Lewerin
Peter Lewerin

Reputation: 13252

The last three, optional, arguments to jsondump are offset, newline, and begin_offset. You can use those to specify strings that are to be used to format the output string. If you don’t specify them, default strings will be used.

If you do specify them, you need to follow the protocol for optional arguments, i.e. if you want to specify begin_offset, you need to specify offset and newline too, etc. In this case, offset and newline are specified to be empty strings, and begin_offset uses its default value.

Try invoking jsondump with dummy values to get an idea of how they are used:

% huddle jsondump [huddle compile {dict * {list {dict d list}}} $arr] <A> <B> <C>
{<B><C><A>"a": [<B><C><A><A>{"c": 1},<B><C><A><A>{<B><C><A><A><A>"d": [<B><C><A><A><A><A>2,<B><C><A><A><A><A>2,<B><C><A><A><A><A>2<B><C><A><A><A>],<B><C><A><A><A>"e": 3<B><C><A><A>}<B><C><A>],<B><C><A>"b": [{<B><C><A><A><A>"f": 4,<B><C><A><A><A>"g": 5<B><C><A><A>}]<B><C>}

A newline and a begin_offset string is inserted around each component, and one or more offset strings are inserted before a component to reflect the indentation level.

json::write uses the indented and aligned subcommands to customize formatting.

Upvotes: 1

Related Questions