jsonpath/wasm/www/index.js

79 lines
1.9 KiB
JavaScript
Raw Normal View History

2019-04-13 22:27:33 +09:00
import * as jsonpath from "jsonpath-wasm";
2019-03-03 00:33:27 +09:00
2019-03-04 23:07:09 +09:00
function getTextarea() {
return document.querySelector('#json-example');
}
2019-03-03 00:33:27 +09:00
2019-03-04 23:07:09 +09:00
function getJsonpathInput() {
return document.querySelector('#jsonpath-input');
}
2019-03-03 00:33:27 +09:00
2019-03-04 23:07:09 +09:00
function getReadBtn() {
return document.querySelector('#read-json');
}
2019-03-03 00:33:27 +09:00
2019-03-04 23:07:09 +09:00
function getReadResult() {
return document.querySelector('#read-result');
}
2019-03-03 00:33:27 +09:00
function getLinks() {
return document.querySelectorAll('.path>a');
}
2019-03-04 23:07:09 +09:00
function initData(url) {
return fetch(url)
.then((res) => res.text())
.then((jsonStr) => getTextarea().value = jsonStr)
.catch(console.error);
}
function initEvent() {
getJsonpathInput().onkeyup = function(e) {
var charCode = (typeof e.which === "number") ? e.which : e.keyCode;
if(charCode == 13) {
read();
}
}
getReadBtn().onclick = function() {
read();
}
getLinks().forEach(function(anchor) {
anchor.href = "#" + encodeURIComponent(anchor.textContent);
});
2019-03-04 23:07:09 +09:00
function read() {
2019-04-07 23:34:16 +09:00
let ret = jsonpath.select(getTextarea().value, getJsonpathInput().value);
2019-03-04 23:07:09 +09:00
if(typeof ret === 'string') {
getReadResult().innerText = ret;
} else {
getReadResult().innerText = JSON.stringify(ret, null, 2);
}
}
}
2019-03-05 14:33:33 +09:00
function readPathParam() {
if(location.href.indexOf('#') > -1) {
readPath()
2019-03-05 14:33:33 +09:00
}
}
function forceClick(ctrl) {
let doc = ctrl.ownerDocument;
let event = doc.createEvent('MouseEvents');
event.initEvent('click', true, true);
event.synthetic = true;
ctrl.dispatchEvent(event, true);
}
function readPath() {
let query = location.href.substring(location.href.indexOf('#') + 1);
let path = decodeURIComponent(query);
getJsonpathInput().value = path;
forceClick(getReadBtn());
}
window.onpopstate = readPath;
2019-03-05 14:33:33 +09:00
initData('data/example.json').then(initEvent).then(readPathParam);