index.js 2.2 KB
Newer Older
B
update  
baiy 已提交
1 2 3 4 5
import Unicode from "../unicode";
import formatter from "../formatter/json";
import csvToJson from './csvToJson';
import tableToJson from './tableToJson';
import jsonToTable from './jsonToTable';
B
baiy 已提交
6
import {stringify} from 'csv-stringify/sync';
B
baiy 已提交
7
import {parse as qsParse, stringify as qsStringify} from "qs";
B
update  
baiy 已提交
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
// 校验语法
export const check = (content) => {
    require('jsonlint').parse(content)
    return content;
}

// 美化
export const beautify = (content) => {
    return formatter.beautify(check(content))
}

// 压缩
export const compress = (content) => {
    return formatter.compress(content)
}

// unicode2zh
export const unicode2zh = (content) => {
    return Unicode.decode(
        content.replace(/\\U[0-9a-fA-F]{4}/g, (item) => {
            // \Uxxxx=>\uxxxx
            return item.replace("\\U", "\\u");
        })
    )
}

// zh2unicode
export const zh2unicode = (content) => {
    if (content) {
        let newStr = ''
        for (let i = 0; i < content.length; i++) {
            let str = content.charAt(i)
            newStr += /[\u4e00-\u9fa5]/.test(str) ? '\\u' + str.charCodeAt(0).toString(16) : str
        }
        return newStr
    }
    return content
}

// 转义
export const escape = (content) => {
    return content.trim().replace(/\\/g, '\\\\').replace(/"/g, '\\"')
}

// 去转义
export const clearEscape = (content) => {
    return content.trim().replace(/\\\\/g, '\\').replace(/\\"/g, '"')
}

// 转get参数
export const toGet = (content) => {
    check(content)
B
baiy 已提交
60
    return qsStringify(JSON.parse(content), {encodeValuesOnly: true})
B
update  
baiy 已提交
61 62 63 64
}

// get转json
export const fromGet = (content) => {
B
baiy 已提交
65
    return beautify(JSON.stringify(qsParse(content.trim())))
B
update  
baiy 已提交
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
}

export default {
    check,
    beautify,
    compress,
    unicode2zh,
    zh2unicode,
    escape,
    clearEscape,
    toGet,
    fromGet,
    csvToJson: (csv = "", option = {}) => {
        return beautify(JSON.stringify(csvToJson(csv, option)))
    },
    jsonToCsv: (json = [], {quoted = false, header = true} = {}) => {
        return stringify(json, {quoted, header})
    },
    tableToJson: (table = "", option = {}) => {
        return beautify(JSON.stringify(tableToJson(table, option)))
    },
    jsonToTable: (json = [], option = {}) => {
        return jsonToTable(json, option)
    },
}