本地读取txt文件将特定字符串转为json数组三条一组

text文件内容

"a":"w11"
"b":"w12"
"c":"w13"
"a":"9"
"b":"w22"
"c":"w23"
"a":"w31"
"b":"w32"
"c":"w33"

逻辑代码 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        .box {
            width: 100%;
            height: calc(100vh - 100px);
            border: 1px solid #000;
        }
    </style>
    }
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/echarts/4.3.0-rc.2/echarts.min.js"></script>
</head>
<body>

<div class="box">
    <span class="click">box</span>
</div>

</body>
<script type="text/plain" src="indexDemo.txt?callback=indexDemo"></script>
<script>
    $('.click').click(function () {
        $.ajax({
            url: './add.txt',
            type: 'GET',
            dataType: 'Text',
            success: function (data) {
                data = JSON.stringify(data)
                let data_1 = data.split('\\n')
                for (var i = 0; i < data_1.length; i++) {
                    if (i == data_1.length - 1) {
                        data_1[i] = data_1[i].substring(1, data_1[i].length - 1)
                    } else {
                        data_1[i] = data_1[i].substring(1, data_1[i].length)
                    }
                    data_1[i] = data_1[i].replace(/\\/g, '');
                    data_1[i] = JSON.parse("{" + data_1[i] + "}")
                }
                console.log(data_1)
                let arr1 = data_1
                let arrall = []
                let wrapObj = {};
                for (let index = 0; index < arr1.length; index++) {
                    let ob = {}
                    ob = arr1[index]
                    if (Object.keys(wrapObj).length < 3) {
                        wrapObj = Object.assign(wrapObj, ob)
                        console.log(wrapObj)
                    } else {
                        console.log('push')
                        arrall.push(wrapObj)
                        wrapObj = {...ob}
                    }
                }
                arrall.push(wrapObj)
                console.log(arrall)

            },
            error: function () {
                alert("错误");
            }
        })
    })

</script>
</html>

打印结果

由于练习变量命名不规范可省略。。。。。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值