Music, Sound Design, and Software Programming

JSON File Parser

When using javascript in MaxMSP you can query most of the attributes of the available objects. Things like the screen co-ordinates, the scripting name and whether the object is included in presentation mode. There are a few things that it cannot tell you with one example being the number of inlets or outlets an object has. One way to do this is to parse the file in the uncompressed text format. MaxMSP files are stored as JSON so reading them inside javascript isn’t too difficult. We can then query any of the values that you can see if you open a file as text. I’ve written a script to load in the parent patch and report object attributes in a few different ways. Here’s the code:

The first section will load the parent file into the object when the patch is opened, this can also be done with the “init” message. It will also turn on the [filewatch] object if it is connected to the second outlet, useful for auto-updating every time the patch is saved. The next section loads the JSON data. It uses the javascript eval function rather than JSON parsing code as we can be fairly sure that the file is formatted properly. Keep in mind that this could cause problems if you make any changes to the code or try to load a corrupted file. The following blocks define functions to describe certain messages which can be sent to the object. These are:

count [class]: reports how many objects of type [class] there are in the patch.

query [attribute]: outputs the value of the [attribute] for each object in the patch.

object [class] [attribute]: outputs the value of the [attribute] for each object of type [class] present in the patch.

name [varname] [attribute]: outputs the value of the [attribute] for each object named [varname] in the patch.

[attribute one] [value] [attribute two]: will output the value of [attribute two] for each object where [attribute one] is equal to [value]. For example “presentation 1 varname” will output all the scripting names of objects included in presentation mode.

Included below is an example patch, uncompressed so Max4 users have a chance of understanding it.

This might not be overwhelmingly useful to everyone but on the off chance that you’ve ever needed to know more than javascript has been willing to tell you before it could be helpful. It is meant to be used in an open patch rather than in a collective where the JSON is bundled in with everything else included in the .mxf file so unfortunately it won’t be much help if you’re dynamically scripting objects in a standalone.

There are other uses for this method. The JSON also includes patch cord information which you otherwise don’t get access to so it could be used to dynamically reconnecting or paste-replace objects programatical. The box details are included in order of creation so you could also get a patch to build itself step by step which could make for some interesting slideshow style tutorials.