1.json.stringify(obj) JS对象 -> JSON字符串
2.JSON.parse(item)JSON字符串 -> JS对象
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta http-equiv="X-UA-Compatible" content="IE=edge" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>JSON常用API</title></head><body><!--1.json是通用的,轻量化的"数据交互格式",用于"前后端数据通信"2.json独立于编程语言,本质是一个格式化字符串3.json借用了js对象字面量的语法,简洁高效,已经替换了传统的XML格式4.json不是js对象,但它可以与js对象之间相互转换数据类型:1.简单类型:number,string,boolean,null2.数组:[...]3.对象:{...},这是关注的重点不支持underfined,没有意义json:本质就是js对象的序列化,字符串表示方法--><script>// 1. JS对象 -> JSON字符串// json.stringify(obj)const user = {id: 1,name: '老马',age: 35,};console.log(user, typeof user);//转为jsonlet json = JSON.stringify(user);console.log(json, typeof json);json = JSON.stringify(user, ['id', 'name']);console.log(json);//在值前传2个空格json = JSON.stringify(user, ['id', 'name'], 2);console.log(json);json = JSON.stringify(user, null, 2);console.log(json);/*** * 与后端数据传输* * ajax 过时了* * 使用:fetch,promise,await等等*/// 2. JSON字符串 -> JS对象let item = `{"id": 1,"name": "手机","price": 1000}`;console.log(item, typeof item);const obj = JSON.parse(item);console.log(obj, typeof obj);let html = `<ul><li>ID:${obj.id}</li><li>品名:${obj.name}</li><li>价格:${obj.price}</li></ul>`;console.log(html);document.body.insertAdjacentHTML('afterbegin',html);</script></body></html>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号