过滤json字段/属性
2023-03-08 本文已影响0人
姬歌
json指定保留字段,过滤其他字段,美化格式。
过滤器
- 把下面代码贴到 “空白文本.txt”,保存后重命名为"栓Q.html",双击打开即可使用。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>json过滤器</title>
</head>
<body>
<h6 style="color: blue;">json保留指定字段,去除多余字段:</h6>
<p style="font-size: smaller">请粘贴/输入json字符串:</p>
<div style="width:fit-content;position:relative;">
<textarea id="txtArea" rows="22" cols="110"></textarea>
<br/>
<button style="position:absolute;right:0;margin-top:10px;" type="button" onclick="clickClear1(this)">clear</button>
</div>
<br/>
<br/>
<p style="font-size: smaller">请输入要保留的字段(keys),英文逗号隔开。仅输入星号“*”则表示全部保留只美化格式。</p>
<span class="blue-key">要保留的keys:</span>
<input style="width:300px;" type="text" id="keys" placeholder="输入要保留的字段名,如'rows,id,name'">
<button style="margin-left:20px;" type="button" onclick="clickClear2(this)">clear</button>
<button style="margin-left:20px;" type="button" onclick="clickAllKeys(this)">*,all-keys</button>
<br/>
<span style="font-size: smaller">当结果json最外层只有一个key,且value是Array时,不要Key只保留Array</span> <input type="checkbox" id="ckbox">
<br/>
<br/>
<br/>
<br/>
<button style="margin-left:30px;" type="button" onclick="clickGo1(this)">GO - 紧凑格式</button>
<button style="margin-left:30px;" type="button" onclick="clickGo2(this)">GO - 美化格式</button>
<br/>
<br/>
<span class="red-key" id="informs1"></span>
<span class="normal-key" id="informs2"></span>
<span class="blue-key" id="informs3"></span>
<br/>
<p style="font-size: smaller">按F12打开调试面板,在"Console"标签下查看输出结果。</p>
<p style="font-size: smaller">按"Ctrl + R"快速刷新/重置页面。</p>
<button class="bottom" type="button" onclick="clickPaste(this)">粘贴测试数据</button>
<p></p>
</body>
<script type="text/javascript">
function clickClear1(argument) {
document.getElementById('txtArea').value = ''
}
function clickClear2(argument) {
document.getElementById('keys').value = ''
}
function clickAllKeys(argument) {
document.getElementById('keys').value = '*'
}
function clickGo1(argument) {
doClick(1)
}
function clickGo2(argument) {
doClick(2)
}
function clickPaste(argument) {
document.getElementById('txtArea').value = testStr
document.getElementById('keys').value = 'rows,id,name'
}
// resultType: 1-紧凑,2-美化
function doClick(resultType) {
document.getElementById('informs1').innerHTML = ''
document.getElementById('informs2').innerHTML = ''
document.getElementById('informs3').innerHTML = ''
let string = document.getElementById('txtArea').value
if (string.length < 5) {
alert('请输入json内容')
return
}
// console.log(string)
let obj = undefined
try{
let ro = JSON.parse(string)
obj = ro
}catch(e) {
console.log(e)
}
// console.log(obj)
if (obj == undefined) {
document.getElementById('informs1').innerHTML = 'json 格式有误,解析失败。'
return
}
let keepKeys = document.getElementById('keys').value
if (keepKeys.length < 1) {
alert('请输入要保留的 keys')
return
}
_keepKeys = keepKeys.split(',')
if (_keepKeys.length == 1 && _keepKeys[0] == '*') {
// 全部保留
}else if (_keepKeys.length < 2) {
alert('keys 至少包含2个key')
return
}
filtKeys(obj)
let finalObj = obj
let isChecked = document.getElementById('ckbox').checked
if (isChecked) {
if (!(obj instanceof Array)) {
let objKeys = getAllKeys(obj)
if (objKeys.length == 1 && ((obj[objKeys[0]]) instanceof Array)) {
finalObj = obj[objKeys[0]]
}
}
}
let jsonString = ''
if (resultType == 1) {
jsonString = JSON.stringify(finalObj)
}else {
jsonString = JSON.stringify(finalObj, null, 2)
}
console.clear()
console.log(jsonString)
// 复制到剪贴板
copyText(jsonString)
// 提示复制结果
let timeStr = new Date().toLocaleTimeString()
let style = resultType == 1 ? '紧凑' : '美化'
document.getElementById('informs1').innerHTML = '内容已复制'
document.getElementById('informs2').innerHTML = ' - ' + timeStr + ' - '
document.getElementById('informs3').innerHTML = style + '格式'
}
function filtKeys(jsonObj) {
if (typeof(jsonObj) == 'object') {
if (jsonObj instanceof Array) {
// console.log('是数组')
for (var i = 0; i < jsonObj.length; i++) {
let oneObj = jsonObj[i]
filtKeys(oneObj)
}
}else{
// console.log('是非数组对象')
for(var key in jsonObj) {
if (isKeepKey(key)) {
filtKeys(jsonObj[key])
}else {
delete jsonObj[key]
}
}
}
}else {
// 非 object 类型,啥也不做
}
}
var _keepKeys = []
function isKeepKey(key) {
if (_keepKeys.length == 1 && _keepKeys[0] == '*') {
return true
}
for (var i = 0; i < _keepKeys.length; i++) {
let kkey = _keepKeys[i]
if (key == kkey) {
return true
}
}
return false
}
function getAllKeys(Obj) {
let keys = []
if (typeof(Obj) == 'object') {
for(var key in Obj) {
keys.push(key)
}
}
return keys
}
//复制文本
function copyText(text) {
var element = createElement(text);
element.select();
element.setSelectionRange(0, element.value.length);
document.execCommand('copy');
element.remove();
// alert("已复制到剪切板");
console.log('已复制到剪切板')
}
//创建临时的输入框元素
function createElement(text) {
var isRTL = document.documentElement.getAttribute('dir') === 'rtl';
var element = document.createElement('textarea');
// 防止在ios中产生缩放效果
element.style.fontSize = '12pt';
// 重置盒模型
element.style.border = '0';
element.style.padding = '0';
element.style.margin = '0';
// 将元素移到屏幕外
element.style.position = 'absolute';
element.style[isRTL ? 'right' : 'left'] = '-9999px';
// 移动元素到页面底部
let yPosition = window.pageYOffset || document.documentElement.scrollTop;
element.style.top = `${yPosition}px`;
//设置元素只读
element.setAttribute('readonly', '');
element.value = text;
document.body.appendChild(element);
return element;
}
const testStr = '{"total":7,"rows":[{"id":"101","name":"张三","address":"地址1"},{"id":"102","name":"李四","address":"地址2"},{"id":"103","name":"王五","address":"地址3"},{"id":"104","name":"老六","address":"地址4"},{"id":"105","name":"鬼脚七","address":"地址5"},{"id":"106","name":"刀八","address":"地址6"},{"id":"107","name":"陈九","address":"地址7"}],"code":0}'
</script>
<style type="text/css">
.bottom {
position: fixed;
bottom: 10px;
left: 20px;
}
.blue-key {
color: blue;
font-size: smaller;
}
.red-key {
color: red;
font-size: smaller;
}
.normal-key {
color: #333333;
font-size: smaller;
}
</style>
</html>