I need to convert this data to JSON format.
Input:
mysql Ver 15.1 Distrib 10.4.22-MariaDB, for Linux (x86_64) using readline 5.1
Connection id: 11725048
Current database:
Current user: cartadmin@localhost
SSL: Not in use
Current pager: stdout
Using outfile: ''
Using delimiter: ;
Server: MariaDB
Server version: 10.2.10-MariaDB-log MariaDB Server
Protocol version: 10
Connection: 127.0.0.1 via TCP/IP
Server characterset: latin1
Db characterset: latin1
Client characterset: utf8
Conn. characterset: utf8
TCP port: 3306
Uptime: 1255 days 11 hours 7 min 4 sec
Threads: 11 Questions: 41743540705 Slow queries: 157520 Opens: 3668268 Flush tables: 47 Open tables: 512 Queries per second avg: 384.832
const input = `
mysql Ver 15.1 Distrib 10.4.22-MariaDB, for Linux (x86_64) using readline 5.1
Connection id: 11725017
Current database:
Current user: cartadmin@localhost
SSL: Not in use
Current pager: stdout
Using outfile: ''
Using delimiter: ;
Server: MariaDB
Server version: 10.2.10-MariaDB-log MariaDB Server
Protocol version: 10
Connection: 127.0.0.1 via TCP/IP
Server characterset: latin1
Db characterset: latin1
Client characterset: utf8
Conn. characterset: utf8
TCP port: 3306
Uptime: 1255 days 10 hours 56 min 30 sec
Threads: 11 Questions: 41743540474 Slow queries: 157520 Opens: 3668268 Flush tables: 47 Open tables: 512 Queries per second avg: 384.834
`;
const lines = input.trim().split('n');
const data = {};
let currentCategory = 'General'; // Default category
for (const line of lines) {
const [key, ...values] = line.trim().split(/s+/);
const value = values.join(' ');
if (key.endsWith(':')) {
currentCategory = key.slice(0, -1);
data[currentCategory] = {};
} else {
data[currentCategory][key] = value;
}
}
const jsonData = JSON.stringify(data, null, 2);
console.log(jsonData);
But I’m not able to achieve an output in JSON format.
I tried executing the above program, but I am getting a JavaScript error.
4
Answers
The error you’re encountering is likely due to an issue with how the data object is being constructed. The error message suggests that you are trying to set a property of an undefined object. It could be related to how you’re handling the currentCategory and creating nested objects in the data structure.
Here’s a modified version of your code that should work correctly and generate the desired JSON output:
try this:
JSON is data objects consisting of attribute–value pairs and arrays. On the input, mysql object need to have ‘:’ to define it as a key value pairs. So the input is in the wrong here.
Try this as an input
JSON convert with the input