JS字符串拼接JSON问题

第一种种拼接json的key会过滤双引号


    var arr = "sequence" + ":" + "[";

    let arrEnd = "]";

    for(let i=0;i<[1,2,3].length;i++){

      arr += "{" +"sequence" + ":" + [1,2,3][i] + "," + "process" + "[" + [[1,2,3],[2,4],[5,4]][i]+"]"+"}"+",";

    }

    let arrs = '{' + arr.substring(0,arr.length-1)+arrEnd + '}';

    console.log(arrs);//{sequence:[{sequence:1,process[1,2,3]},{sequence:2,process[2,4]},{sequence:3,process[5,4]}]}

    

第二种拼接数组[1,2,3]会被当字符串处理


    var arr = "sequence" + ":" + "[";

    let arrEnd = "]";

    for(let i=0;i<[1,2,3].length;i++){

      arr += "{ \"sequence\": [1,2,3][i], \"process\": [[[1,2,3],[2,4],[5,4]][i]]}"+",";

    }

    let arrs = JSON.stringify('{' + arr.substring(0,arr.length-1)+arrEnd + '}');

    console.log(JSON.parse(arrs)); /*{sequence:[{ "sequence": [1,2,3][i], "process": [[[1,2,3],[2,4],[5,4]][i]]},{ "sequence": [1,2,3][i], "process": [[[1,2,3],[2,4],[5,4]][i]]},{ "sequence": [1,2,3][i], "process": [[[1,2,3],[2,4],[5,4]][i]]}]}*/

求一种拼接完能和json格式一样的方法,然后要能取的到值


汪汪一只猫
浏览 452回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript