'Javascript - looking for most efficient way to convert a JSON object into a null (<0x00>)-terminated byte array

Per https://www.jsonrpc.org/specification I need a JSON object returned as a byte array, contatenated with <0x00>.

Consider this object:

{"jsonrpc":"2.0","method":"StatusGet","id":"1","params":0}

Returned as <0x00>-terminated byte array:

[123,34,106,115,111,110,114,112,99,34,58,34,50,46,48,34,44,34,109,101,116,104,111,100,34,58,34,83,116,97,116,117,115,71,101,116,34,44,34,105,100,34,58,34,49,34,44,34,112,97,114,97,109,115,34,58,48,125,0]

From examples found elsewhere, here's what I currently have that works (in a Nodered function node, which is fed into a TCP request node):

function fnStringMessage(str){
    
    let bytes = Buffer.from(str)
    bytes = []
    for (let i=0; i<str.length; i++){
        bytes.push(str.charCodeAt(i))
    }
    bytes.push(0)

    return (bytes)
}

let ss = JSON.stringify(msg.payload)

msg.payload = Buffer.from(fnStringMessage(ss))

return msg;

However I'm a noob and using a for loop looks a bit turtle to me. Looking for the hare, and any other suggestions to simplify this further. Thanks



Solution 1:[1]

You can append a zero byte to the string, then convert that into a Buffer.

function fnStringMessage(str){
  return Buffer.from(str + "\0");
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Barmar