Skip to content

Instantly share code, notes, and snippets.

@zzbo
Last active March 2, 2019 13:46
Show Gist options
  • Save zzbo/04d8651029f366545c7138897c096bb2 to your computer and use it in GitHub Desktop.
Save zzbo/04d8651029f366545c7138897c096bb2 to your computer and use it in GitHub Desktop.
mysql <5.7 query result transfer to json
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>mysql query result to json</title>
<style>
.mysql-query-result-input, .mysql-query-result-input-wrap {
width: 600px;
height: 500px;
float: left;
}
.transfer-result-input {
width: 600px;
height: 500px;
float: left;
margin-left: 20px;
}
.transfer-btn {
width: 606px;
height: 30px;
margin-top: 10px;
}
</style>
</head>
<body>
<div class="mysql-query-result-input-wrap">
<textarea id="js-mysql-query-result-input" class="mysql-query-result-input">
+--------+-------------------------+-------------------------------+
| id | history_id | key |
+--------+-------------------------+-------------------------------+
| 1 | 7320 | sdf |
| 2 | 12176 | cc |
| 3 | 9470 | bb |
| 4 | 22018 | dd |
| 5 | 14869 | ee |
| 6 | 12209 | ff |
| 7 | 10143 | gg |
+--------+-------------------------+-------------------------------+
</textarea>
<button id="js-transfer-btn" class="transfer-btn">transfer to json</button>
</div>
<textarea id="js-transfer-result-input" class="transfer-result-input"></textarea>
<script>
const mysqlQueryResultInput = document.getElementById('js-mysql-query-result-input');
const transferResultInput = document.getElementById('js-transfer-result-input');
const transferBtn = document.getElementById('js-transfer-btn');
const splitPartReg = /\|\s(.+)\s\|\n/g;
const arrayItemTrim = function(arr) {
return arr.map((item) => {
return item.trim();
});
}
transferBtn.addEventListener('click', function() {
const mysqlQueryResult = mysqlQueryResultInput.value;
const output = [];
let keys;
let matchResult;
let index = 1;
while((matchResult = splitPartReg.exec(mysqlQueryResult)) !== null) {
matchResult = arrayItemTrim(matchResult[1].split('|'));
if (!keys) {
keys = matchResult;
continue;
}
let lineResult = {};
keys.forEach((item, index) => {
lineResult[item] = matchResult[index];
});
output.push(lineResult);
}
console.log('output', output);
transferResultInput.value = JSON.stringify(output, null, 2);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment