How to convert raw text data into json format?

Viewed 57

I am getting the response from an API mentioned below, I have been trying to convert the below data into a JSON array, but I am not able to convert it.

found=100
items[0].Detail.Address=192.168.1.4
items[0].Detail.Type=CGI
items[0].Device=
items[0].Level=0
items[0].Time=2022-09-15 11:10:12
items[0].Type=Log In
items[0].User=admin
items[1].Detail.Address=192.168.1.4
items[1].Device=
items[1].Level=0
items[1].Time=2022-09-15 11:09:37
items[1].Type=Log Out
items[1].User=admin

I want to convert this data into an Array of JSON.

The expected result:

[
  {
    "Detail": {
      "Address": "192.168.1.4",
      "Type": "CGI"
    },
    "Device": "",
    "Level": 0,
    "Time": "2022-09-15 11:10:12",
    "Type": "Log In",
    "User": "admin"
  },
  {
    "Detail": {
      "Address": "192.168.1.4"
    },
    "Device": "",
    "Level": 0,
    "Time": "2022-09-15 11:09:37",
    "Type": "Log Out",
    "User": "admin"
  }
]
1 Answers

Lucky I've been writing a lot of code that converts "x.y.z" into object lately

here you go

const data = `found=100
items[0].Detail.Address=192.168.1.4
items[0].Detail.Type=CGI
items[0].Device=
items[0].Level=0
items[0].Time=2022-09-15 11:10:12
items[0].Type=Log In
items[0].User=admin
items[1].Detail.Address=192.168.1.4
items[1].Device=
items[1].Level=0
items[1].Time=2022-09-15 11:09:37
items[1].Type=Log Out
items[1].User=admin
items[2].Detail.Address=192.168.1.4
items[2].Detail.Type=CGI
items[2].Device=
items[2].Level=0
items[2].Time=2022-09-15 11:09:37
items[2].Type=Log In
items[2].User=admin`;

const assign = (obj, str, value) => {
    str.split('.').reduce((acc, part, index, array) => {
        let newValue = isNaN(value) ? value : +value;
        if (index < array.length - 1) {
            if (isNaN(array[index + 1])) {
                newValue = {};
            } else {
                newValue = [];
            }
        }
        return acc[part] = acc[part] || newValue;
    }, obj);
    return obj;
}
const result = data.split(/\n/).map(v => {
    const [key, ...rest] = v.split('=');
    const value = rest.join('=');
    return [key.replaceAll('[', '.').replaceAll(']', ''), value];
}).reduce((acc, [key, value]) => assign(acc, key, value), {});
console.log(JSON.stringify(result.items, null, 4));

Related