1. 程式人生 > 其它 >前端js資料處理為Json串和拼接Json字串,全

前端js資料處理為Json串和拼接Json字串,全

前端js拼接Json字串,全

示例1:數組裡面含物件

<script>    
    var  params = [];
    for(var i = 0; i < 3; i++){
        var param = [];
        param.push("one");
        param.push("two");
        param.push("three");
        params.push({"group":i,"param":param});
    }
    
    var json = JSON.stringify(params);//JSON.stringify() 方法用於將 JavaScript 值轉換為 JSON 字串。
    alert(json);
</script>

組成的json串:

[{"group":0,"param":["one","two","three"]},{"group":1,"param":["one","two","three"]},{"group":2,"param":["one","two","three"]}]

示例2:物件裡面含陣列

var object = {};
var params = [];
    
for(var i = 0; i < 3; i++){
    var obj = {};    
    obj[i] = "abc";
    params.push(obj);
    
}
object['name'] = 'jack';
object['age'] = 25;
object['data'] = params;
 
var json = JSON.stringify(object);
console.log(json);

組成的json串:

{"name":"jack","age":25,"data":[{"0":"abc"},{"1":"abc"},{"2":"abc"}]}

推薦一個線上編輯JavaScript的網站https://runjs.cn/