Casting Python Dictionary as JSON Object via Script Transform on a Tag Binding

Hello!

I am trying to get data from a UDT (with OPC tags connected to a PLC) to dynamically load interlocks for a perspective view. Part of this UDT has a bool value “Used” which is true when that interlock is being used in the PLC.

To display this, I am trying to bring in the UDT via tag binding (direct for now, indirect later) and use a script transform to filter out the objects where “Used” is false. I have it pretty much figured out, except that my result is just a PyString and not an object and I cannot seem to figure out how to cast this correctly so that I can use each interlock’s object values as params for a view repeater.

Here is the script:

            import json
            dict = system.util.jsonDecode(str(value))
            for key in dict:
                            if dict[key]["Used"] == 0:
                                            del dict[key]
            newValue = json.dumps(dict, indent = 4)
            return newValue

Here is a screenshot of the code for more reference:

Here is the result of that script on the binding:
jsonObjectScreenshot2

    my_dict = system.util.jsonDecode(str(value))
    for key in my_dict:
        if my_dict[key]["Used"] == 0:
            del my_dict[key]
    return my_dict
  1. In your example, dict is already a format which will be recognized as an object in Perspective, but…
  2. You shouldn’t name you variable dict because dict is essentially a type in python, which makes it a reserved word. You can usually do this without issue, but it could also cause problems which can be hard to troubleshoot because you think you’re looking at a variable when you could perhaps be creating a whole new dict. In my example, I replaced your dict variable with my_dict to avoid shadowing the dict keyword.
1 Like

Thanks for the reply! This worked to solve the initial problem, however I actually need an array (I thought I needed an object but I was wrong).

jsonObjectScreenshot4

I had originally named each object 0 through 6, but the python dict was not a fan so I added an “i” in front.

Ok, after some google searching and experimenting, I just needed to declare it as a list via:

list(my_dict.values())

Thanks for your help!!

return my_dict.items()

Will return a list of your objects, but if you just need the values they contain, then yes, my_dict.values() will work, and you shouldn’t need to wrap it in a list.

return my_dict.values()