export JSON data

2023-08-11  本文已影响0人  niccky
  1. 获取 JSON 数据片段
function run(input, content) {
    if(!input || typeof input !== 'string') return content;

    const inputText = input.trim();
    if(!inputText.length) return content;
        
    let [pathText='', fieldText=''] = inputText.split(':');
    const obj = typeof content === 'string'
        ? JSON.parse(content)
        : content;
    pathText = pathText.trim();
    fieldText = fieldText.trim();
    const getFields = (text, ch) => {
        return text.split(ch).filter(Boolean).map(r=>r.trim());
    }
    const paths = getFields(pathText, '.');
    const fields = getFields(fieldText,',');

    const fnArray = (data) => {
        const tmp = data[0];
        if(fields.filter(f => tmp[f]).length) {
            return data.reduce((ret, cur) => {
                const ans = {};
                for(const f of fields) {
                    ans[f] = cur[f];
                }
                ret.push(ans);
                return ret;
            }, []);
        }
        return data;
    }

    const fnObject = data => {
        return fields.filter(f => data[f]).reduce((ret, key) => {
            ret[key] = data[key];
            return ret;
        }, {});
    } 
    if(pathText === '') {
        if(fieldText === '') {
            return content;
        } 
        return Array.isArray(obj)
            ? fnArray(obj)
            : typeof obj === 'object'
            ? fnObject(obj)
            : obj;
    }

    let data = obj;
    for(const key of paths) {
        data = data[key];
    }

    if(fieldText == '') {
        return data;
    }

    return Array.isArray(data)
            ? fnArray(data)
            : typeof data === 'object'
            ? fnObject(data)
            : data;
}
  1. 片段数据处理
function transform(data) {
    if(Array.isArray(data)) {
        const headers = Object.keys(data[0]).join(',');
        if(headers === '') return data;
        const ans = data.reduce((acc, cur) => {
            const ret = [];
            for(let k of Object.keys(cur)) {
                ret.push(`${JSON.stringify(cur[k])}`);
            }
            acc.push(ret);
            return acc;
        }, []);
        ans.unshift(headers);
        return ans.join('\n');
    }

    if(typeof data === 'object') {
        return JSON.stringify(data);
    }

    return data;
}
  1. 导出 csv 文件
function fileExport(data) {
    const blob = new Blob([data], {type: 'text/csv;charset=UTF-8'});
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    const name = prompt("download filename", "demo.csv");
    a.download = name;
    a.click();
    URL.revokeObjectURL(a.href);
}
  1. 测试
fileExport(
    transform(
        run(
            'data:id,url,username,owner',
            tests(),
        )
    )
);
  1. 附录
    测试数据
function tests(){
    return {
        a: 1,
        b: 2,
        x: [1,2],
        y: [3,4],
        c: {
            d: 3,
            e: 4,
            f: 5,
            h: [
                1,2,3,4,5
            ],
            i: {
                j: 8,
                k: 9,
                m: 10,
                n: 12,
            },
            u: [
                {
                    id: 1,
                    name: 'name1',
                    p: 'p1'
                },
                {
                    id: 2,
                    name: 'name2',
                    p: 'p2'
                },
                {
                    id: 3,
                    name: '3',
                    p: 'p3'
                }
            ]
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读