This is because your str
object above is defined as an Array
with 1 member, which is a Hash
, which has several key/value pairs, the last of which is "projects"
, whose value is an Array
with 1 member, which is a Hash
.
IT is not yet a JSON string.
To use JSON functionality, you normally need to …
require "json"
… but I think SketchUp loads it up at startup anyway,…
but you should still “require” it so as to declare a dependency.
Then to produce a JSON string that you wish to send to a HtmlDialog, to produce a JS Object (which is similar to a Ruby OpenStruct
,) or a JS Array, you start on the Ruby side with a Hash
or OpenStruct
, or a Ruby Array
…
hash = {
"org_id"=>54,
"org_name"=>"",
"creator"=>"Noone",
"role"=>"admin",
"projects"=>[
{"project_id"=>310, "name"=>"26Dec", "description"=>""}
]
}
# Create the JSON string ...
json_str = hash.to_json # uses double quotes
# Pass the JSON string to a web dialog ...
dialog.execute_script(%[set_projects('#{json_str}');]
… then on the JS side something like … (untested)
// JavaScript global variable
var ProjectList = null;
function set_projects( json_str ) {
ProjectList = JSON.parse(json_str);
}
function task() {
if (ProjectList.org_id == 54) {
// do some task
if (ProjectList.projects[0].project_id == 310) {
// Hey we are getting somewhere ...
}
}
}
So, it is important to realize that Ruby Arrays are converted to JS Arrays, …
and Ruby Hashes converted to JS Objects. (This is why is is called JavaScript Object Notation.)
Then when you get JSON
strings back from a webdialog and wish to convert back to Ruby …
hash = JSON::load(json_str)
… or simply use the “smart” JSON::[]
method …
hash = JSON[json_str]
RUBY REFERENCES
JAVASCRIPT REFERENCES: