Problem with json in custom node

Hi everyone

<script type="text/javascript">
    RED.nodes.registerType('InitSVI',{
        category: 'matrice_svi',
        color: '#EF4040',
        defaults: {
            name: {value:"",required:true},
            statName:{value:""},
            globalProperties:{value:""} //"", [] , {} // Object , JSON 
        },
        inputs: 0,
        outputs: 1,
        icon: "icons/InitSVI.svg",
        label: function() {
            return this.name||"InitSVI";
        },
        oneditprepare: function () {
            this.editor = RED.editor.createEditor({
                id: 'node-input-editor',
                mode: 'ace/mode/json',
                value: this.globalProperties
            });
        },
        oneditsave: function() {
            this.globalProperties = this.editor.getValue();
            this.editor.destroy();
            delete this.editor;
        },
        oneditcancel: function() {
            this.editor.destroy();
            delete this.editor;
        },
    });
</script>

<script type="text/html" data-template-name="InitSVI">

    <div class="form-row">
        <label for="node-input-name"><i class="fa fa-tag"></i>Name</label>
        <input type="text" id="node-input-name" placeholder="Name">
    </div>
    <div class="form-row">
        <label for="node-input-statName"><i class="fa fa-tag"></i>statName</label>
        <input type="text" id="node-input-statName" placeholder="statName">
    </div>
    <label for="node-input-editor"><i class="fa fa-tag"></i>globalProperties</label>
    <div style="height: 90%; min-height:150px;width: 90%;margin: auto;" class="node-text-editor" id="node-input-editor"></div>

</script>

hello everyone,

i created a custom node that has a text editor to put json inside, except that when i import this node it converts the value to string, except that i would like it to keep the type JSON, i tried to change the type of the field "value" but without success. If anyone has an idea, I'm a taker

Riri

The text editor only knows how to edit strings - so the getValue() is giving you a string.

If you really want to store the parsed version instead, you could do:

this.globalProperties = JSON.parse(this.editor.getValue())

(and use JSON.stringify(...) in oneditprepare to convert it back to a string for the text editor to use.

However you will need to handle the case where the user enters invalid JSON etc as that will cause the JSON.parse to throw an error.

1 Like

Just adding a reminder to that suggestion - always wrap JSON.parse and JSON.stringify in try/catch blocks because they can (and do) fail fairly easily.

For the record, JSON is always a string. When you parse it then it becomes a javascript object. It is no longer JSON.