How can I get DICT to JavaScript
Hi,
How can I get a dictionary from the DICT object (embed 1) to the JavaScript code? I know, I can import any JSON/YAML file to JS via "myArray.import_yaml();", but I would like to get the data from the internal [dict] object.
Thanks
Hi Martin,
Bang the dictionary in to a JS object with a function called dictionary(), e.g.:
function dictionary()
{
var theDictionary = new Dict(arguments[0]);
var k = theDictionary.getkeys();
for(i = 0; i < k.length; i++) post(k[i] + "\n");
}
hth
I used (a more ornate version of ) this simplified code a couple of years ago for a project, some of which was gleaned from this forum. The dict_to_jsobj function is called recursively to jsonify hierarchical dict structures. Maybe it is no longer necessary in max 7 (I'm still on max 6)?
outlets = 1;
var currentDict = new Object();
function parse(dictName) {
var theDict = new Dict(dictName);
currentDict = dict_to_jsobj(theDict); //currentDict is a js object
}
function bang()
{
output=JSON.stringify(currentDict); //, null, "\t"
outlet (0, output);
}
function write(p){
var jase = JSON.stringify(currentDict,null,'\t');
var path = p;
var fout = new File(path,"write","TEXT");
if (fout.isopen) {
fout.eof = 0;
fout.writeline(jase);
fout.close();
post("\nJSON Write",path);
} else {
post("\ncould not create json file: " + path);
}
}
// returns or includes null if there is a dict without containing data.
function dict_to_jsobj(dict) {
if (dict == null) return null;
var o = new Object();
var keys = dict.getkeys();
if (keys == null || keys.length == 0) return null;
if (keys instanceof Array) {
for (var i = 0; i < keys.length; i++)
{
var value = dict.get(keys[i]);
if (value && value instanceof Dict) {
value = dict_to_jsobj(value);
}
o[keys[i]] = value;
}
} else {
var value = dict.get(keys);
if (value && value instanceof Dict) {
value = dict_to_jsobj(value);
}
o[keys] = value;
}
return o;
}
Hi hth,
I tried this, but the console says: k is null.
What I did:
[bang] > left inlet of [dict] most left outlet of dict > [prepend dictionary] > js inlet.
Shoul it work this way?
Working example is here:
https://cycling74.com/forums/javascript-and-dict
Thanks!
For the archives, much simpler ways to convert a js object from and to dict (now?) exist:
function dictionary(dictName)
{
var inputDict = new Dict(dictName)
var jsObject = JSON.parse(inputDict.stringify())
}
function bang()
{
var outputDict = new Dict()
outputDict.parse(JSON.stringify(jsObject))
}
Hi Mattijs,
can you give an equally simple example of a the ARRAY object (named), to and from JS? (plus a simple maxpat)
Br Jan
It looks like arrays arrive in JS the same way lists do, so if you want to get the separate elements inside the array, they can be found as function arguments for the anything function:
function anything() {
var args = arrayfromargs(messagename, arguments)
for each (arg in args) {
post(arg, "\n")
}
}
