How to pass json object as input to python script through exec node?

please find the node-red code below:

[
    {
        "id": "1ff7a51a41da7b57",
        "type": "tab",
        "label": "Flow 2",
        "disabled": false,
        "info": "",
        "env": []
    },
    {
        "id": "7cb19c907c1ff65c",
        "type": "inject",
        "z": "1ff7a51a41da7b57",
        "name": "",
        "props": [
            {
                "p": "payload"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "{\"foo\": \"bar\", \"baz\": 42}",
        "payloadType": "str",
        "x": 190,
        "y": 160,
        "wires": [
            [
                "7bfbe73e74b613d2"
            ]
        ]
    },
    {
        "id": "410e2cc3223cf46c",
        "type": "debug",
        "z": "1ff7a51a41da7b57",
        "name": "debug 1",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "true",
        "targetType": "full",
        "statusVal": "",
        "statusType": "auto",
        "x": 640,
        "y": 160,
        "wires": []
    },
    {
        "id": "7bfbe73e74b613d2",
        "type": "exec",
        "z": "1ff7a51a41da7b57",
        "command": "python D:\\PythonCode\\hello.py",
        "addpay": "",
        "append": "",
        "useSpawn": "false",
        "timer": "",
        "winHide": false,
        "oldrc": false,
        "name": "",
        "x": 410,
        "y": 160,
        "wires": [
            [
                "410e2cc3223cf46c"
            ],
            [],
            []
        ]
    }
]

And my python code-

import json
import sys

# Read the JSON object from the command-line argument
json_string = sys.argv[1]

# Parse the JSON object into a Python object
json_obj = json.loads(json_string)

# Access the properties of the JSON object
foo_value = json_obj["foo"]
baz_value = json_obj["baz"]

# Print the values to the console
print(f"foo = {foo_value}")
print(f"baz = {baz_value}")

The first thing you need to do is to tick Append Payload in the exec node. Then, if it still doesn't work connect debug nodes to all three outputs of the exec node, set then to Output Complete Message, and check the contents of them all to see if there is an error message.

Before that however, does it work if you run it in a command window? If so then exactly what command line are you entering?

Command failed: python D:\PythonCode\hello.py {"foo": "bar", "baz": 42}
Traceback (most recent call last):
  File "D:\PythonCode\hello.py", line 8, in <module>
    json_obj = json.loads(json_string)
  File "C:\Users\11113313\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Users\11113313\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\11113313\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

Im getting above error and the command which Im running is this "python D:\PythonCode\hello.py"

Do you mean you get that error when you run it in a command window? If so then you need to fix that. It won't run in node-red if it won't run in a command window.

maybe this will help you

There is a thread on stackexchange which suggests that sys.argv[1] strips the double quotes from the element names and values.

Another thread offers

import argparse
import json

# Set up the argument parser
parser = argparse.ArgumentParser()
parser.add_argument('JSON', metavar='json',type=str, help='JSON to parse')

args = parser.parse_args()

# Get JSON data
json_str = args.JSON

# Parse JSON data
json_data = json.loads(json_str)
print(json_data["foo"])

I don't have Node-red on Windows so I can't test if the above works with a json string passed from NR

No in command widow it works fine. but in node red Im getting error.

I asked earlier that you show us exactly the command line you are using that works.

If you have got this working then please tell us that and what the problem was, so that others can benefit. Do not leave the thread dangling.

I notice that you left the only other thread you started dangling too. That is not good forum manners.

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.