json.stringfy()將對象、數組轉換成字符串
//1 var student = new Object(); student.name = "Lanny"; student.age = "25"; student.location = "China"; var json = JSON.stringify(student); alert(json); //alert(student);
如圖所示:
假如,我們不要這個函數,而直接alert(student),結果如下:
以下示例使用 JSON.parse 將 JSON 字符串轉換成對象。 var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}'; var contact = JSON.parse(jsontext); document.write(contact.surname + ", " + contact.firstname); // Output: Aaberg, Jesper 以下示例演示了如何使用 JSON.stringify 將數組轉換成 JSON 字符串,然后使用 JSON.parse 將該字符串重新轉換成數組。 var arr = ["a", "b", "c"]; var str = JSON.stringify(arr); document.write(str); document.write ("<br/>"); var newArr = JSON.parse(str); while (newArr.length > 0) { document.write(newArr.pop() + "<br/>"); } // Output: // ["a","b","c"] // c // b // a