js 中 json.stringfy()將對象、數組轉換成字符串


 

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

  來自於 :https://www.cnblogs.com/panmy/p/5925986.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM