Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a labels array "serializer/deserializer" #483

Closed
mStirner opened this issue Jul 11, 2024 · 2 comments
Closed

Add a labels array "serializer/deserializer" #483

mStirner opened this issue Jul 11, 2024 · 2 comments
Labels

Comments

@mStirner
Copy link
Member

mStirner commented Jul 11, 2024

Convert label(s) dot notoation to a object.
e.g.

let labels = [
    "oh.notifications.smtp.enabled=true",
    "oh.notifications.smtp.topic=Hello World",
    "[email protected]", // wrong - gerts converted to object instead of string
    "oh.notifications.enabled=true",
    "oh.notifications.states[]=foo",
    "oh.notifications.states[]=bar",
    "oh.history.states[]=*",
    "oh.history.duration=3600",
    "private=true",
    "my-super-label=value",
    `oh.json=${JSON.stringify(json)}`
];

will be:

{
  oh: {
    notifications: {
      smtp: {
        enabled: 'true',
        topic: 'Hello World',
        sender: '[email protected]'
      },
      enabled: 'true',
      states: [ 'foo', 'bar' ]
    },
    history: { states: [ '*' ], duration: '3600' },
    json: '{"timemstamp":1720719319460,"bool":true,"zero":null,"obj":{"str":"Hello from json"}}'
  },
  private: 'true',
  'my-super-label': 'value'
}
marc@workstation:~/projects/OpenHaus/plugins/oh-plg-smtp-sender$ nodemon test.js 
[nodemon] 3.1.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node test.js`
labels [
  'oh.notifications.smtp.enabled=true',
  'oh.notifications.smtp.topic=Hello World',
  '[email protected]',
  'oh.notifications.enabled=true',
  'oh.notifications.states[]=foo',
  'oh.notifications.states[]=bar',
  'oh.history.states[]=*',
  'oh.history.duration=3600',
  'private=true',
  'my-super-label=value',
  'oh.json={"timemstamp":1720719321281,"bool":true,"zero":null,"obj":{"str":"Hello from json"}}'
]
parsedObj {
  oh: {
    notifications: {
      smtp: {
        enabled: 'true',
        topic: 'Hello World',
        sender: '[email protected]'
      },
      enabled: 'true',
      states: [ 'foo', 'bar' ]
    },
    history: { states: [ '*' ], duration: '3600' },
    json: '{"timemstamp":1720719321281,"bool":true,"zero":null,"obj":{"str":"Hello from json"}}'
  },
  private: 'true',
  'my-super-label': 'value'
}
function arrayToObject(labels) {

    let result = {};

    labels.forEach((label, i) => {

        let [path, value] = label.split("=");
        let parts = path.split('.');
        let current = result;

        for (let i = 0; i < parts.length; i++) {

            let key = parts[i];
            let isLast = (i === parts.length - 1);
            let isArray = key.endsWith('[]');

            if (isArray) {
                key = key.slice(0, -2);
            }

            if (isLast) {

                //value = (value === "true") ? true : (value === "false") ? false : value;

                if (isArray) {

                    if (!current[key]) {
                        current[key] = [];
                    }

                    current[key].push(value);

                } else {

                    current[key] = value;

                }

            } else {

                if (!current[key]) {
                    current[key] = {};
                }

                current = current[key];

            }

        }

    });

    return result;

}


function objectToArray(obj, prefix = "") {

    let result = [];

    for (let key in obj) {
        let value = obj[key];
        let newKey = prefix ? `${prefix}.${key}` : key;

        if (typeof value === 'object' && !Array.isArray(value)) {
            result = result.concat(objectToArray(value, newKey));
        } else if (Array.isArray(value)) {
            value.forEach(val => {
                result.push(`${newKey}[]=${val}`);
            });
        } else {
            result.push(`${newKey}=${value}`);
        }
    }

    return result;

}

Could be added as static methods to the Labels class (class.labels.js)

@mStirner
Copy link
Member Author

mStirner commented Jul 20, 2024

Improved version:

const util = require("util");

function arrayToObject(labels) {

    let result = {};

    labels.forEach((label, i) => {

        let [path, value] = label.split("=");
        let parts = path.split('.');
        let current = result;

        for (let i = 0; i < parts.length; i++) {

            let key = parts[i];
            let isLast = (i === parts.length - 1);
            let isArray = key.endsWith('[]');

            if (isArray) {
                key = key.slice(0, -2);
            }

            if (isLast) {

                //value = (value === "true") ? true : (value === "false") ? false : value;

                if (isArray) {

                    if (!current[key]) {
                        current[key] = [];
                    }

                    current[key].push(value);

                } else {

                    current[key] = value;

                }

            } else {

                if (!current[key]) {
                    current[key] = {};
                }

                current = current[key];

            }

        }

    });

    return result;

}


function objectToArray(obj, prefix = "") {

    let result = [];

    for (let key in obj) {
        let value = obj[key];
        let newKey = prefix ? `${prefix}.${key}` : key;

        if (typeof value === 'object' && !Array.isArray(value)) {
            result = result.concat(objectToArray(value, newKey));
        } else if (Array.isArray(value)) {
            value.forEach(val => {
                result.push(`${newKey}[]=${val}`);
            });
        } else {
            result.push(`${newKey}=${value}`);
        }
    }

    return result;

}

const json = {
    timemstamp: Date.now(),
    bool: true,
    zero: null,
    obj: {
        str: "Hello from json"
    }
}

// Beispielaufruf
let labels = [
    "oh.notifications.smtp.enabled=true",
    "oh.notifications.smtp.topic=Hello World",
    "[email protected]", // wrong - gerts converted to object instead of string
    "oh.notifications.enabled=true",
    "oh.notifications.states[]=foo",
    "oh.notifications.states[]=bar",
    "oh.history.states[]=*",
    "oh.history.duration=3600",
    "private=true",
    "my-super-label=value",
    `oh.json=${JSON.stringify(json)}`
];


console.log("labels", labels)

/*
const ohLabels = labels.filter((label) => {
    return !label.startsWith("oh.");
});
*/

const parsedObj = arrayToObject(labels);
const arrayFromObj = objectToArray(parsedObj);

console.log("parsedObj", util.inspect(parsedObj, false, 100, true));
console.log("arrayFromObj", arrayFromObj);


const same = (() => {

    let valid = labels.every((label) => {
        return arrayFromObj.includes(label);
    });

    valid &= arrayFromObj.length === labels.length;

    return Boolean(valid);

})();

console.log("Array same", same);

Result:

labels [
  'oh.notifications.smtp.enabled=true',
  'oh.notifications.smtp.topic=Hello World',
  '[email protected]',
  'oh.notifications.enabled=true',
  'oh.notifications.states[]=foo',
  'oh.notifications.states[]=bar',
  'oh.history.states[]=*',
  'oh.history.duration=3600',
  'private=true',
  'my-super-label=value',
  'oh.json={"timemstamp":1721501606716,"bool":true,"zero":null,"obj":{"str":"Hello from json"}}'
]
parsedObj {
  oh: {
    notifications: {
      smtp: {
        enabled: 'true',
        topic: 'Hello World',
        sender: '[email protected]'
      },
      enabled: 'true',
      states: [ 'foo', 'bar' ]
    },
    history: { states: [ '*' ], duration: '3600' },
    json: '{"timemstamp":1721501606716,"bool":true,"zero":null,"obj":{"str":"Hello from json"}}'
  },
  private: 'true',
  'my-super-label': 'value'
}
arrayFromObj [
  'oh.notifications.smtp.enabled=true',
  'oh.notifications.smtp.topic=Hello World',
  '[email protected]',
  'oh.notifications.enabled=true',
  'oh.notifications.states[]=foo',
  'oh.notifications.states[]=bar',
  'oh.history.states[]=*',
  'oh.history.duration=3600',
  'oh.json={"timemstamp":1721501606716,"bool":true,"zero":null,"obj":{"str":"Hello from json"}}',
  'private=true',
  'my-super-label=value'
]
Array same true

@mStirner mStirner added the idea label Jul 21, 2024
@mStirner
Copy link
Member Author

For what purpose?
If i rember, reopen.

@mStirner mStirner closed this as not planned Won't fix, can't repro, duplicate, stale Oct 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant