No json in script nodes?

Hi!

I’m trying to use json inside of a python script node, but I get this error:

# Error: NameError: file <string> line 14: global name 'json' is not defined

Obviously I do import json before using it in the node, still the same thing. cmds works though.

What am I missing here? Or is it somehow not supported by script nodes?

I did some quick testing in the Expression Editor
Script node commands appear to be MEL, not python.
You have to wrap python code as string args in the MEL python() command:

python("import json");
python("print dir(json)");

That works with the expression editor Test Script button at least

I can’t import maya.cmds as cmds without wrapping in this way

[edit] also see this thread

The scriptNode has has a sourceType attribute which toggle between mel and python. If you set the sourceType to 1, your scriptNode will run in python

The error message here makes me think python more than mel.
Not sure how script-nodes handle their namespace scopes, but my guess is that like a lot of things in maya, they handle it poorly.

python("import json");
python("print json");
<module 'json' from 'C:\Program 
Files\Autodesk\Maya2018\bin\python27.zip\json\__init__.py'>   
python("del json");
python("print json");
 # Error: line 1: NameError: file <maya console> line 1: name 'json' is not defined #
1 Like

@Mambo4 As @Theodox said scriptNode can use either mel or python depending on sourceType.

@Theodox Are you suggesting I should run scriptNode as MEL and wrap commands in python("") instead if I need json to work? That’d be duh

For now I just went with hard-coding required information directly into the scriptnode but that’s a bit too rigid. On the other hand it’s faster than reading json from an attribute. Not that it matters much for something like space switch matching though.

I was just pointing out how you can generate that error. It’s unlikely that you did what I did – but basically a NameError means either a missing import or an accidental destruction of the variable name that the module was imported with.

If you add import sys; print (sys.modules) into your script it’ll tell you if you have actually successfully imported json