jQueryで配列や連想配列などからJSON形式に変換する方法をいろいろ検証しました。また、JSON形式から配列に変換する方法を試しています。╰(*´︶`*)╯
配列(連想配列)からJSON形式へ変換
検証①
変換方法
var json1 = JSON.stringify(<配列>);
コード①
$(function(){
console.clear();
var arrayList1 = [1,2,3,4,5];
var json1 = JSON.stringify(arrayList1);
console.log(json1);
var arrayList2 = [1,['test1','test2'],[3,4,5],6,7];
var json2 = JSON.stringify(arrayList2);
console.log(json2);
});
結果①
"[1,2,3,4,5]"
"[1,['test1','test2'],[3,4,5],6,7]"
検証②
コード①
$(function(){
console.clear();
var arrayList1 = {"name":"taro","age":"15"};
var json1 = JSON.stringify(arrayList1);
console.log(json1);
var arrayList2 = {"name":"taro","age":"15","other":[1,2,3]};
var json2 = JSON.stringify(arrayList2);
console.log(json2);
var arrayList3 = [{"name":"taro","age":"15"}
, {"name":"hanako","age":"34"}];
var json3 = JSON.stringify(arrayList3);
console.log(json3);
});
結果②
"{'name':'taro','age':'15'}"
"{'name':'taro','age':'15','other':[1,2,3]}"
"[{'name':'taro','age':'15'},{'name':'hanako','age':'34'}]"
JSON形式から配列(連想配列)へ変換
検証①
変換方法
var arrayList1 = JSON.parse(<JSON形式の文字列>);
コード①
$(function(){
console.clear();
var json1 = '[1,2,3,4,5]';
var arrayList1 = JSON.parse(json1);
console.log(arrayList1);
var json2 = '[1,["test1","test2"],[3,4,5],6,7]';
var arrayList2 = JSON.parse(json2);
console.log(arrayList2);
});
結果①
[1, 2, 3, 4, 5]
[1, ["test1", "test2"], [3, 4, 5], 6, 7]
検証②
コード②
$(function(){
console.clear();
var json1 = '{"name":"taro","age":"15"}';
var arrayList1 = JSON.parse(json1);
console.log(arrayList1);
var json2 = '{"name":"taro","age":"15","other":[1,2,3]}';
var arrayList2 = JSON.parse(json2);
console.log(arrayList2);
var json3 = '[{"name":"taro","age":"15"}, {"name":"hanako","age":"34"}]';
var arrayList3 = JSON.parse(json3);
console.log(arrayList3);
});
結果②
Object {
age: "15",
name: "taro"
}
Object {
age: "15",
name: "taro",
other: [1, 2, 3]
}
[Object {
age: "15",
name: "taro"
}, Object {
age: "34",
name: "hanako"
}]