Seperate a String and save it to variable

Hey there,

I want to split a string and save it to different variables.
The content of the different lines have a variable length.

image

The result should be:
Variable "Status": (Variable length of text)
Variable "StateOfCharge": (Variable length of number)
Variable "LocalizationScore":(Variable length of number)

If you need more information let me know.

Firstly

If you have any control over how that string is constructed in the first place, you would be better off making it an Object or JSON String.

e.g. ' {"Status": "xxx", "StateOfChange": 97.5, "LocalizationScore": 0.694} ' can be converted immediately and perfectly using the JSON node or JSON.parse(yourString)

After all, JSON stands for JavaScript Object Notation


However...

If you have no control over the format of that text then here is a small function that should help.

Function to split lines of colon separated text into a JS Object

var obj = {}, re = new RegExp('(.*?):(.*?)(?:,|$)','gm')
msg.payload.replace(re, (_, key, value) => obj[key.trim()] = value.trim())
msg.payload = obj
return msg;

Proof...

image

Once the value is an object, you can use the nifty debug to copy path tools. (see below)


Canned Text...

There’s a great page in the docs (Working with messages : Node-RED) that will explain how to use the debug panel to find the right path to any data item.

Pay particular attention to the part about the buttons that appear under your mouse pointer when you over hover a debug message property in the sidebar.

BX00Cy7yHi

1 Like

Thank you very much :slight_smile:

This helps pretty much already.

My coding in a function node looks like the following:

// String umwandeln in JSON
var payload = JSON.stringify(msg);

//Trennen der Benennung und diesen die Werte zuweisen
var obj = {}, re = new RegExp('(.*?):(.*?)(?:,|$)','gm')
msg.payload.replace(re, (_, key, value) => obj[key.trim()] = value.trim())
msg.payload = obj

And the messages looks accurate:
image

============================================

Now next step which I actually dont know.

I want to post it in a postgres database.
I know how to create the database and so on and I know the format, so this is clear.

What i dont know:
How to seperate the three "Values" I have to the collumn.

So I want to put the Status, the Akku and the Lokal to the right collumn, but I dont know how to write the correct function^^

At the end the row of the function looks like:

msg.payload = "INSERT INTO AGV2 (Zeit, AGV, Error, Status, Code, Akku, Lokalisierung) \
                    VALUES "+curdate+", "+topic+", "+error+", "+Status+", "+code+", "+Akku+", "+Lokal+");"

But how to link the values out of the Object, or how to set these to a variable?

image

there are plenty of threads on this and often info & demos built into the postgres node you install.

I would suggest - do a bit searching on the forum.

If you get stuck, start a new thread titled appropriate to the problem.

As for which postgres node, i have had success with node-red-contrib-postgresql - YMMV

Hey Steve, thank you very much for your help.
I solved the issue with posting in postgres and managed it to put the JSON Objekt Message into the corresponding columns.

Of course I wanna show what I have done and how I make it work^^
Maybe there are better solutions, but for non programming skills I feel quite happy :smiley:

For the explanation what we are doing:
We are connecting 3 TCP-IP devices via Telnet and collect the information.
Then we are bundling it into one message

[
    {
        "id": "8f43d406f36016bd",
        "type": "join",
        "z": "10e3370b6bdaf657",
        "name": "",
        "mode": "custom",
        "build": "string",
        "property": "payload",
        "propertyType": "msg",
        "key": "topic",
        "joiner": "",
        "joinerType": "str",
        "accumulate": false,
        "timeout": "",
        "count": "3",
        "reduceRight": false,
        "reduceExp": "",
        "reduceInit": "",
        "reduceInitType": "num",
        "reduceFixup": "",
        "x": 790,
        "y": 1200,
        "wires": [
            [
                "db3ff737df91f8d3"
            ]
        ]
    },
    {
        "id": "1614aa952d6ab3f8",
        "type": "switch",
        "z": "10e3370b6bdaf657",
        "name": "",
        "property": "payload",
        "propertyType": "msg",
        "rules": [
            {
                "t": "cont",
                "v": "StateOfCharge",
                "vt": "str"
            },
            {
                "t": "cont",
                "v": "LocalizationScore:",
                "vt": "str"
            },
            {
                "t": "cont",
                "v": "Status:",
                "vt": "str"
            }
        ],
        "checkall": "true",
        "repair": false,
        "outputs": 3,
        "x": 250,
        "y": 1200,
        "wires": [
            [
                "35ce4a6361a852b9"
            ],
            [
                "35ce4a6361a852b9"
            ],
            [
                "35ce4a6361a852b9"
            ]
        ]
    },
    {
        "id": "ce908f70b56a1746",
        "type": "postgres",
        "z": "10e3370b6bdaf657",
        "postgresdb": "d2e3a056.2fdc1",
        "name": "",
        "output": true,
        "perrow": false,
        "rowspermsg": "1",
        "return_on_error": false,
        "limit_queries": "0",
        "limit_by": "",
        "limit_value": "",
        "limit_drop_intermediate": false,
        "limit_drop_if_in_queue": false,
        "outputs": true,
        "x": 1340,
        "y": 1320,
        "wires": [
            [
                "3d33198f041c931e"
            ]
        ]
    },
    {
        "id": "3d33198f041c931e",
        "type": "debug",
        "z": "10e3370b6bdaf657",
        "name": " ",
        "active": true,
        "tosidebar": true,
        "console": true,
        "tostatus": true,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "payload",
        "statusType": "auto",
        "x": 1490,
        "y": 1320,
        "wires": []
    },
    {
        "id": "3b900db7145e84c1",
        "type": "msg-speed",
        "z": "10e3370b6bdaf657",
        "name": "Store2Postgres/min",
        "frequency": "min",
        "interval": 1,
        "estimation": true,
        "ignore": false,
        "pauseAtStartup": false,
        "topicDependent": false,
        "x": 1215,
        "y": 1320,
        "wires": [
            [],
            [
                "ce908f70b56a1746"
            ]
        ],
        "l": false
    },
    {
        "id": "f4af9133.082d8",
        "type": "debug",
        "z": "10e3370b6bdaf657",
        "name": "",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "false",
        "x": 1510,
        "y": 1200,
        "wires": []
    },
    {
        "id": "14752b19cb149f16",
        "type": "function",
        "z": "10e3370b6bdaf657",
        "name": "",
        "func": "// String umwandeln in JSON\nvar payload = JSON.stringify(msg);\n\n//Trennen der Benennung und diesen die Werte zuweisen\nvar obj = {}, re = new RegExp('(.*?):(.*?)(?:,|$)','gm')\nmsg.payload.replace(re, (_, key, value) => obj[key.trim()] = value.trim())\nmsg.payload = obj\n// Payload ist jetzt JS Object\n\n// Datum aus Datumsbaustein\ncurdate = msg.curtimeDate;\n\n//payload = msg.payload;\n\n// Topic beschreibt, welcher AGV\ntopic = msg.topic;\nAGV = topic;\n\nif (( payload.match(\"Going*\")) || (payload.match == (\"going*\")))\n{\n\tevents = payload;\n\terror = \"on the way\";\n\tcode = \"0\";\n\ttopic = topic\n       }\nelse if ( payload.match(\"Aufnahme*\"))\n{\n\tevents = payload;\n\terror = \"no Error\";\n\tcode = \"1\";\n\ttopic = topic\n    } \n    else if ( payload.match(\"Abgabe*\"))\n{\n\tevents = payload;\n\terror = \"OK\";\n\tcode = \"2\";\n\ttopic = topic\n    }\n    else if (( payload.match(\"Error*\")) || (payload.match == (\"error*\"))|| (payload.match == (\"Interrupted*\"))) \n{\n\tevents = \"error\";\n\terror = payload;\n\tcode = \"3\";\n\ttopic = topic\n       }\n    else if (( payload.match(\"Docked*\")) || (payload.match == (\"DockingState*\"))|| (payload.match == (\"Interrupted*\"))) \n{\n\tevents = payload;\n\terror = \"Docking\";\n\tcode = \"4\";\n\ttopic = topic\n       }\n\nelse if (payload == payload)\n{\n\tevents = payload;\n\terror = \"--\";\n\tcode = \"5\";\n\ttopic = topic\n}\n\n\n\n\nmsg.code = code;\n//code = msg.code;\n\nmsg.error = error;\n//error = msg.error;\n\nmsg.Status = obj.Status;\nStatus = msg.Status;\n\nmsg.Lokal = obj.Lokal;//.substring(2);\nLokal = msg.Lokal;\n\nmsg.Akku = obj.Akku;\nAkku = msg.Akku;\n\n\n\nmsg.payload = \"INSERT INTO AGV2 (Zeit, AGV, Error, Status, Code, Akku, Lokalisierung) \\\n                    VALUES \"+curdate+\", \"+topic+\", \"+error+\", \"+Status+\", \"+code+\", \"+Akku+\", \"+Lokal+\");\"\nreturn msg;\n\n",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 1060,
        "y": 1200,
        "wires": [
            [
                "f4af9133.082d8",
                "7471ac53bca34bd7"
            ]
        ]
    },
    {
        "id": "db3ff737df91f8d3",
        "type": "moment",
        "z": "10e3370b6bdaf657",
        "name": "",
        "topic": "",
        "input": "notime",
        "inputType": "msg",
        "inTz": "Europe/Berlin",
        "adjAmount": 0,
        "adjType": "days",
        "adjDir": "add",
        "format": "'YYYY-MM-DD HH:mm:ss'",
        "locale": "en-US",
        "output": "curtimeDate",
        "outputType": "msg",
        "outTz": "Europe/Berlin",
        "x": 915,
        "y": 1200,
        "wires": [
            [
                "14752b19cb149f16"
            ]
        ],
        "l": false
    },
    {
        "id": "7471ac53bca34bd7",
        "type": "function",
        "z": "10e3370b6bdaf657",
        "name": "Save Data",
        "func": "lmsg = msg;\n\nmsg={};\n\nmsg.queryParameters = {};\nmsg.queryParameters.param1 = lmsg.curtimeDate;\nmsg.queryParameters.param2 = lmsg.topic;\nmsg.queryParameters.param3 = lmsg.error;\nmsg.queryParameters.param4 = lmsg.Status;\nmsg.queryParameters.param5 = lmsg.code;\nmsg.queryParameters.param6 = lmsg.Akku;\nmsg.queryParameters.param7 = lmsg.Lokal;\n\nreturn msg;\n/*\nvar AGV = msg.topic;\nvar Status1 = flow.get('Status');\nvar Akku = flow.get('StateOfCharge');\nvar Lokalisierung = flow.get('LocalizationScore');\n*/",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 1070,
        "y": 1260,
        "wires": [
            [
                "7cfc469d5dbf35a9"
            ]
        ]
    },
    {
        "id": "7cfc469d5dbf35a9",
        "type": "template",
        "z": "10e3370b6bdaf657",
        "name": "Transfer Data",
        "field": "payload",
        "fieldType": "msg",
        "format": "handlebars",
        "syntax": "mustache",
        "template": "insert into agv2 (Zeit, AGV, error, Status, Code, Akku, Lokalisierung) values($param1, $param2, $param3, $param4, $param5, $param6, $param7)",
        "output": "str",
        "x": 1080,
        "y": 1320,
        "wires": [
            [
                "3b900db7145e84c1"
            ]
        ]
    },
    {
        "id": "35ce4a6361a852b9",
        "type": "change",
        "z": "10e3370b6bdaf657",
        "name": "",
        "rules": [
            {
                "t": "change",
                "p": "payload",
                "pt": "msg",
                "from": "Status:",
                "fromt": "str",
                "to": "Status:",
                "tot": "str"
            },
            {
                "t": "change",
                "p": "payload",
                "pt": "msg",
                "from": "StateOfCharge:",
                "fromt": "str",
                "to": "Akku:",
                "tot": "str"
            },
            {
                "t": "change",
                "p": "payload",
                "pt": "msg",
                "from": "LocalizationScore",
                "fromt": "str",
                "to": "Lokal:",
                "tot": "str"
            }
        ],
        "action": "",
        "property": "",
        "from": "",
        "to": "",
        "reg": false,
        "x": 610,
        "y": 1200,
        "wires": [
            [
                "8f43d406f36016bd"
            ]
        ]
    },
    {
        "id": "bd5402e43c46bcc8",
        "type": "link in",
        "z": "10e3370b6bdaf657",
        "name": "",
        "links": [
            "941bb69213013c08"
        ],
        "x": 115,
        "y": 1200,
        "wires": [
            [
                "1614aa952d6ab3f8"
            ]
        ]
    },
    {
        "id": "d2e3a056.2fdc1",
        "type": "postgresdb",
        "cfgname": "LocalPostgres",
        "hostname": "0.0.0.0",
        "port": "5432",
        "db": "postgres",
        "ssl": false
    }
]

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