提交 b8aaa25c 编写于 作者: B baiy 提交者: ninecents

#105

上级 ddbe3fc9
<template> <template>
<div> <div>
<div style="border: 1px solid #dcdee2;border-radius: 4px;"> <heightResize :append="['.page-option-block','.tool-json-mode-get']" @resize="resize">
<code-editor v-model="current.content" :auto-height="220" language="json"></code-editor> <Row :gutter="10">
</div> <Col :span="24-jsonInputCol" v-if="isMode('from_csv')">
<option-block :style="{textAlign:'center'}"> <csvToJson @change="(json)=>current.content = json" @saveToolData="saveToolData" :height="height" v-model="current.from_csv" />
<FormItem> </Col>
<ButtonGroup> <Col :span="24-jsonInputCol" v-if="isMode('from_table')">
<Button type="primary" @click="handle(k)" v-for="(v,k) in type" :key="k">{{v}}</Button> <tableToJson @change="(json)=>current.content = json" @saveToolData="saveToolData" :height="height" v-model="current.from_table" />
</Col>
<Col :span="jsonInputCol">
<input-block top="4px">
<code-editor :height="`${height}px`" :placeholder="`${$t('json_input')}JSON`" v-model="current.content" language="json"></code-editor>
<template slot="extra">
<Button shape="circle" icon="md-code" v-if="!isMode('default')" @click="setMode('default')"></Button>
</template>
</input-block>
</Col>
<Col :span="24-jsonInputCol" v-if="isMode('to_csv')">
<jsonToCsv :json="current.content" :height="height" v-model="current.to_csv" @saveToolData="saveToolData" />
</Col>
<Col :span="24-jsonInputCol" v-if="isMode('to_table')">
<jsonToTable :json="current.content" :height="height" v-model="current.to_table" @saveToolData="saveToolData" />
</Col>
<Col :span="24-jsonInputCol" v-if="isMode('object')">
<jsonToObject :json="current.content" :height="height" v-model="current.to_object" @saveToolData="saveToolData" />
</Col>
</Row>
</heightResize>
<option-block style="padding-top: 10px" disable-padding class="tool-json-mode-get" v-if="isMode('to_get') || isMode('from_get')">
<Input v-if="isMode('to_get')" type="textarea" :rows="3" :value="getOutput" :placeholder="`Get ${$t('json_output')}`"></Input>
<Input v-else type="textarea" :rows="3" v-model="current.get.input" :placeholder="`Get ${$t('json_input')} var1=value1&var2=value2`"></Input>
</option-block>
<option-block center class="page-option-block">
<FormItem class="tool-json-button">
<ButtonGroup class="tool-json-item">
<Button type="primary" @click="simple('beautify')">{{ $t('json_format') }}</Button>
<Button type="primary" @click="simple('compress')">{{ $t('json_compress') }}</Button>
</ButtonGroup> </ButtonGroup>
<Dropdown @on-click="(name)=>simple(name)" class="tool-json-item">
<Button type="primary">
{{ $t('json_escape') }}
<Icon type="ios-arrow-up" />
</Button>
<DropdownMenu slot="list">
<DropdownItem name="escape">{{ $t('json_add_escape') }}</DropdownItem>
<DropdownItem name="clearEscape">{{ $t('json_clear_escape') }}</DropdownItem>
</DropdownMenu>
</Dropdown>
<Dropdown @on-click="(name)=>simple(name)" class="tool-json-item">
<Button type="primary">
{{ $t('json_unicode') }}
<Icon type="ios-arrow-up" />
</Button>
<DropdownMenu slot="list">
<DropdownItem name="unicode2zh">{{ $t('json_unicode_to_zh') }}</DropdownItem>
<DropdownItem name="zh2unicode">{{ $t('json_zh_to_unicode') }}</DropdownItem>
</DropdownMenu>
</Dropdown>
<Dropdown @on-click="(name)=>setMode(name)" class="tool-json-item">
<Button type="primary">
{{ $t('json_get') }}
<Icon type="ios-arrow-up" />
</Button>
<DropdownMenu slot="list">
<DropdownItem name="to_get">JSON => Get</DropdownItem>
<DropdownItem name="from_get">Get => JSON</DropdownItem>
</DropdownMenu>
</Dropdown>
<Button class="tool-json-item" type="primary" @click="setMode('object')">{{ $t('json_object') }}</Button>
<Dropdown @on-click="(name)=>setMode(name)" class="tool-json-item">
<Button type="primary">
{{ $t('json_csv') }}
<Icon type="ios-arrow-up" />
</Button>
<DropdownMenu slot="list">
<DropdownItem name="to_csv">JSON => CSV</DropdownItem>
<DropdownItem name="from_csv">CSV => JSON</DropdownItem>
</DropdownMenu>
</Dropdown>
<Dropdown @on-click="(name)=>setMode(name)" class="tool-json-item">
<Button type="primary">
{{ $t('json_table') }}
<Icon type="ios-arrow-up" />
</Button>
<DropdownMenu slot="list">
<DropdownItem name="to_table">JSON => Table</DropdownItem>
<DropdownItem name="from_table">Table => JSON</DropdownItem>
</DropdownMenu>
</Dropdown>
</FormItem> </FormItem>
</option-block> </option-block>
</div> </div>
</template> </template>
<script> <script>
import Unicode from "./library/unicode" import jsonInstance from "./library/json"
import codeEditor from "./components/codeEditor"; import codeEditor from "./components/codeEditor";
import heightResize from "./components/heightResize";
import jsonToObject from "./library/json/components/jsonToObject";
import csvToJson from "./library/json/components/csvToJson";
import tableToJson from "./library/json/components/tableToJson";
import {dispatchWindowResize} from "../../tool/event";
import jsonToCsv from "./library/json/components/jsonToCsv";
import jsonToTable from "./library/json/components/jsonToTable";
export default { export default {
components: { components: {
jsonToCsv,
jsonToTable,
codeEditor, codeEditor,
heightResize,
csvToJson,
jsonToObject,
tableToJson
}, },
created () { computed:{
this.current = Object.assign(this.current, this.$getToolData('content')) jsonInputCol(){
if (this.isMode('object')){
return 10
}
if (this.isMode('from_csv') || this.isMode('from_table') || this.isMode('to_csv') || this.isMode('to_table')){
return 12
}
return 24
}, },
methods: { getOutput(){
handle (v) { if (!this.isMode('to_get')){
if (this.current.content) { return "";
switch (v) {
case 'format':
try {
let content = this.current.content.trim()
if (!content) {
return this.$Notice.error({ title: '错误提示', desc: '请输入内容' })
} }
require('jsonlint').parse(content) return this.errorHandle(()=>{
this.current.content = JSON.stringify(JSON.parse(this.current.content), null, 4) return jsonInstance.toGet(this.current.content)
} catch (error) {
this.$Notice.error({
title: '错误提示',
desc: error.message,
}) })
return },
} fromGet(){
break if (this.isMode('from_get') && this.current.get.input.trim()){
case 'compress': return this.current.get.input;
try {
this.current.content = JSON.stringify(JSON.parse(this.current.content.trim()))
} catch (e) {
this.current.content = this.current.content.replace(/\n/g, '').replace(/\r/g, '')
} }
break return "";
case 'escape':
this.current.content = this.current.content.trim().
replace(/\\/g, '\\\\').
replace(/"/g, '\\"')
break
case 'clearEscape':
this.current.content = this.current.content.trim().
replace(/\\\\/g, '\\').
replace(/\\"/g, '"')
break
case 'unicode2zh':
this.current.content = this.unicode2zh()
break
case 'zh2unicode':
this.current.content = this.zh2unicode()
break
case 'get':
try {
const httpBuildQuery = require('http-build-query');
let content = this.current.content.trim()
if (!content) {
return
} }
require('jsonlint').parse(content) },
this.current.content = httpBuildQuery(JSON.parse(this.current.content)) watch:{
} catch (error) { fromGet(val){
this.$Notice.error({ if (val){
title: '错误提示', this.errorHandle(()=>{
desc: error.message, this.setContentAndSaveToolData(jsonInstance.fromGet(val))
}) })
return
} }
break
case 'clear':
this.current.content = ''
break
default:
return
} }
this.$clipboardCopy(this.current.content) },
this.$saveToolData(this.current) created() {
this.$initToolData()
},
methods: {
resize(height){
this.height = height
},
errorHandle(callback){
try {
return callback()
} catch (e) {
this.$Message.error(this.$t('json_error', [e.message]).toString())
} }
return ""
}, },
unicode2zh () { isMode(mode){
return Unicode.decode( return mode === this.current.mode
this.current.content.replace(/\\U[0-9a-fA-F]{4}/g,(item)=>{ },
// \Uxxxx=>\uxxxx setMode(mode){
return item.replace("\\U","\\u"); this.current.mode = mode
this.$nextTick(() => {
dispatchWindowResize()
}) })
) },
}, // 简单处理
zh2unicode () { simple(type) {
let content = this.current.content this.errorHandle(()=>{
if (content) { this.current.content = this.current.content.trim()
let newStr = '' if (!this.current.content) {
for (let i = 0; i < content.length; i++) { throw new Error(this.$t('json_json_input_empty').toString())
let str = content.charAt(i)
newStr += /[\u4e00-\u9fa5]/.test(str) ? '\\u' + str.charCodeAt(0).toString(16) : str
} }
return newStr // 保存操作前数据
this.saveToolData(true)
if (!(type in jsonInstance)) {
throw new Error("type error")
} }
return content this.current.content = jsonInstance[type](this.current.content)
this.saveToolData()
this.$Message.success(this.$t('json_complete').toString())
})
}, },
saveToolData(force = false){
this.$saveToolData(this.current, force)
}, },
data () { setContentAndSaveToolData(content){
this.current.content = content
this.saveToolData()
}
},
data() {
return { return {
current: { current: {
content: '', content: '',
get: {
input: ""
}, },
type: { to_object:{},
'format': '格式化/校验', from_csv:{},
'compress': '压缩', from_table:{},
'escape': '转义', to_csv:{},
'clearEscape': '去除转义', to_table:{},
'unicode2zh': 'Unicode转中文', mode: "default"
'zh2unicode': '中文转Unicode',
'get': '转GET参数',
'clear': '清空数据',
}, },
height:100
} }
}, },
} }
</script> </script>
<style scoped>
.tool-json-button .ivu-btn {
padding: 0 10px;
}
.tool-json-button .tool-json-item{
margin-right: 5px;
}
</style>
export const beautify = (code, option = {}) => { import prettier from "prettier/standalone";
return objectBeautify(JSON.parse(code.trim()), option) import parserJson5 from "prettier/parser-babel";
export const beautify = (code, {tab = 4} = {}) => {
return prettier.format(code, {
parser: "json5",
plugins: [parserJson5],
quoteProps: "preserve",
trailingComma: "none",
tabWidth: tab,
printWidth: 1
})
} }
export const objectBeautify = (codeObject, option = {}) => { export const objectBeautify = (codeObject, option = {}) => {
return JSON.stringify(codeObject, null, "tab" in option ? option.tab : 4) return beautify(JSON.stringify(codeObject), option)
} }
// eslint-disable-next-line no-unused-vars // eslint-disable-next-line no-unused-vars
export const compress = (code, options = {}) => { export const compress = (code, options = {}) => {
try { let result = []
return JSON.stringify(JSON.parse(code.trim()), null, 0) for (let i = !1, o = 0, r = (code = code.split("\n").join(" ")).length; o < r; o++) {
} catch (e) { let a = code.charAt(o);
return code.replace(/\n/g, '').replace(/\r/g, '') i && a === i ? "\\" !== code.charAt(o - 1) && (i = !1) : i || '"' !== a && "'" !== a ? i || " " !== a && "\t" !== a || (a = "") : i = a
result.push(a)
} }
return result.join("")
} }
export default { export default {
beautify, compress,objectBeautify beautify, compress, objectBeautify
} }
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册