jsontcl

TCL json2dict usage


Using the example from the json TCL library.

https://core.tcl-lang.org/tcllib/doc/9f7971e476/embedded/www/tcllib/files/modules/json/json.html

I am failing to run it successfully.

package require json                    
1.3.3

set data [::json::json2dict {
    "Image": {
        "Width":  800,
        "Height": 600,
        "Title":  "View from 15th Floor",
        "Thumbnail": {
            "Url":    "http://www.example.com/image/481989943",
            "Height": 125,
            "Width":  "100"
        },
        "IDs": [116, 943, 234, 38793]
    }
} ]

dict get $data Image
missing value to go with key

dict keys $data
missing value to go with key

Update:

With proposed change by Schelte Bron the below works OK. Notice the extra braces!

set data [::json::json2dict {{
    "Image": {
        "Width":  800,
        "Height": 600,
        "Title":  "View from 15th Floor",
        "Thumbnail": {
            "Url":    "http://www.example.com/image/481989943",
            "Height": 125,
            "Width":  "100"
        },
        "IDs": [116, 943, 234, 38793]
    }
}} ]

Solution

  • Consider how Tcl parses your json2dictcommand: There's the command itself, followed by a single braced literal argument. The braces are not part of the argument value, they are just quoting characters around the value. This means that your actual json data looks like this:

    "Image": {
        "Width":  800,
        "Height": 600,
        "Title":  "View from 15th Floor",
        "Thumbnail": {
            "Url":    "http://www.example.com/image/481989943",
            "Height": 125,
            "Width":  "100"
        },
        "IDs": [116, 943, 234, 38793]
    }
    

    That is not valid json. A json object must be braced.

    If you are going to do anything more than just very simple json, I would recommend using a proper json parser. One that would raise an error for invalid input. As mentioned by glenn jackman, there's rl_json. But also tdom and sqlite3 include a json parser. If you are already using one of those packages in your program, you get a json parser for free.