JSON转换成字符串
使用:JSON.stringify()
let str = JSON.stringify(user);
样例代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <script> let user={ name: 'Keafmd', sex : '男', age : 18, //永远18 height:187 } let str =JSON.stringify(user); console.log(str); // {"name":"Keafmd","sex":"男","age":18,"height":187} // 也可以转多组 let users=[ { name: 'Keafmd', sex : '男', age : 18, //永远18 height:187 }, { name: '牛哄哄的柯南', sex : '男', age : 19, height:188 }, { name: '牛哄哄的小兰', sex : '女', age : 18, height:173 },] let strs =JSON.stringify(users); console.log(strs); // [{"name":"Keafmd","sex":"男","age":18,"height":187}, //{"name":"牛哄哄的柯南","sex":"男","age":19,"height":188}, //{"name":"牛哄哄的小兰","sex":"女","age":18,"height":173}] </script> </body> </html>
效果截图:
字符串转换成JSON
使用:JSON.parse()
样例代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <script> let str = '{"name":"Keafmd","sex":"男","age":18,"height":187}'; // 字符串,单引号引起来 console.log("str: "+str); let user_new = JSON.parse(str); // 转为JSON console.log(user_new); </script> </body> </html>
效果截图: