Blogger Information
Blog 94
fans 0
comment 0
visits 92653
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
【JS】JSON与常用API(stringify与parse)
可乐随笔
Original
537 people have browsed it

JSON与常用API

总结:

1.json.stringify(obj) JS对象 -> JSON字符串
2.JSON.parse(item)JSON字符串 -> JS对象

HTML示范:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>JSON常用API</title>
  8. </head>
  9. <body>
  10. <!--
  11. 1.json是通用的,轻量化的"数据交互格式",用于"前后端数据通信"
  12. 2.json独立于编程语言,本质是一个格式化字符串
  13. 3.json借用了js对象字面量的语法,简洁高效,已经替换了传统的XML格式
  14. 4.json不是js对象,但它可以与js对象之间相互转换
  15. 数据类型:
  16. 1.简单类型:number,string,boolean,null
  17. 2.数组:[...]
  18. 3.对象:{...},这是关注的重点
  19. 不支持underfined,没有意义
  20. json:本质就是js对象的序列化,字符串表示方法
  21. -->
  22. <script>
  23. // 1. JS对象 -> JSON字符串
  24. // json.stringify(obj)
  25. const user = {
  26. id: 1,
  27. name: '老马',
  28. age: 35,
  29. };
  30. console.log(user, typeof user);
  31. //转为json
  32. let json = JSON.stringify(user);
  33. console.log(json, typeof json);
  34. json = JSON.stringify(user, ['id', 'name']);
  35. console.log(json);
  36. //在值前传2个空格
  37. json = JSON.stringify(user, ['id', 'name'], 2);
  38. console.log(json);
  39. json = JSON.stringify(user, null, 2);
  40. console.log(json);
  41. /**
  42. * * 与后端数据传输
  43. * * ajax 过时了
  44. * * 使用:fetch,promise,await等等
  45. */
  46. // 2. JSON字符串 -> JS对象
  47. let item = `
  48. {
  49. "id": 1,
  50. "name": "手机",
  51. "price": 1000
  52. }
  53. `;
  54. console.log(item, typeof item);
  55. const obj = JSON.parse(item);
  56. console.log(obj, typeof obj);
  57. let html = `
  58. <ul>
  59. <li>ID:${obj.id}</li>
  60. <li>品名:${obj.name}</li>
  61. <li>价格:${obj.price}</li>
  62. </ul>
  63. `;
  64. console.log(html);
  65. document.body.insertAdjacentHTML('afterbegin',html);
  66. </script>
  67. </body>
  68. </html>
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post