JSON

JSON

1、概述:

json是一种数据格式,他广泛应用于数据传输,(目前大部分的数据传输的格式都是采用json(跨平台 不区分语言)restful接口 就是使用json数据进行传输的)

2、json的表示形式

(1)数组[]

var jsonStr = '[]'

(2)对象{}

var jsonStr = '{}'

(3)对象的表现形式: 包括数组和对象

var jsonObj = [
      	               {“name” : “张三”, age” : 33 },
      	               { “name” : “李四”, “age” : 44 }
	          ]

(4)字符串的表现形式: 包括数组和对象的字符串 

var jsonStr = ‘[{“name” : “张三”, “age” : 33}, {“name” : “李四”, “age” : 44}]’;

3、解析json数据

var lrcObj = {"sgc":false,"sfy":false,"qfy":false,"lrc":{"version":1,"lyric":"
[00:00.000] 作词 : 交易子\n[00:01.000] 作曲 : 交易子\n[00:02.000] 编曲 : 交易子
\n[00:30.069]记忆中的海岸线没我记的那么长远\n[00:37.072]本该撕心裂肺的想念也没我想的那么热
烈\n[00:44.393]我不可能变得连告别都做不到体面\n[00:52.193]毕竟那天之前的事我也不想再经历一
遍\n[00:57.929](ok I should probably stop right there because that's the biggest
lie ever and I'm the biggest joke ever. I never stopped thinking about it. I
still do.)\n[00:58.552]\n[00:59.049]Does everyone\n[01:03.136]keep repeating
their mistakes\n[01:06.673]Or am I the only one\n[01:10.201]trapped in such
fate\n[01:12.456]\n[01:12.968]I was your\n[01:13.872]Lucky
charm\n[01:17.336]Pretty babe\n[01:19.969]Upper arm tattoo
designer\n[01:23.330]Only receiver of flowers you ever sent\n[01:26.730]I miss
your\n[01:27.656]Killing charm\n[01:31.056]Pretty face\n[01:34.456]Reckless
adventures\n[01:37.345]Where I got abandoned in the
end\n[01:40.712]\n[01:42.520]All that pain and misery, is it worth it?
\n[01:47.128]Sarah Lynn? Sarah Lynn?\n[01:49.978]Is it worth it?
\n[01:52.521]Sarah Lynn?\n[01:54.394]\n[01:55.448]你是否也会在下午五点从昏睡惊醒
\n[02:01.857]鼻尖和后背的汗珠 眼眶里凝结的水雾\n[02:08.784]黄昏特别版孤独 看太阳落幕
\n[02:16.376]但那个太阳是我人生最后一次甘甜的痛苦\n[02:21.689]\n[02:22.584]Is
life\n[02:26.136]always this hard\n[02:29.513]or is it just
when\n[02:32.929]you're a kid?\n[02:35.258]\n[02:35.624]I’m
gonna\n[02:36.192]Change my number\n[02:39.592]Smash my
house\n[02:42.984]Deactivate all my credit cards\n[02:46.481]Disappear into the
sea\n[02:49.232]You’re gonna\n[02:49.856]Take another
painkiller\n[02:53.369]Open another vermouth\n[02:56.800]Smoke another
cigarette\n[03:00.106]Forget everything about me\n[03:03.249]Life and death,
energy and peace. If I stop today, it was still worth it. Even the terrible
mistakes that I made and would have unmade if I could. The pains that have
burned me and scarred my soul, it was worth it, for having been allowed to walk
where I've walked, which was to hell on Earth, heaven on Earth, back again,
into, under, far in, and above.\n[03:04.456]\n[03:06.008]so
easily\n[03:08.401]Like it was nothing\n[03:11.864]But to me\n[03:14.065]It was
everything\n"},"tlyric":{"version":0,"lyric":""},"code":200}

获取上述歌词

var str = lrcObj.lrc.lyric
var lines = str.split('\n')
for(line of lines){
console.log(line.split(']')[1])
}

JSON格式的要求 里面的key必须是" "括起来的

4、一般数据是从后台获取 他返回给的json格式的数据是字符串(虽然对应的js可以解析json格式 但是后台如果给你的是字符串的话 那么你就需要进行序列化和反序列化

(1)序列化(将一个内容写入到另一个东西里面叫序列化)

JSON序列化就是将JSON对象(对象或数组)变成JSON字符串的过程; 和JSON解析相反;  

var user = {
username:
'
jack',
password:"123"
}
//toString方法 打印栈地址
console.log(user.toString())
//将对应的对象变成json格式的字符串
console.log(JSON.stringify(user))

序列化的核心就是将对应的对象变成json格式的字符串

JSON.stringify(对象)

(2)反过来从一个东西里面获取另一个东西 叫反序列化(将字符串变成我们能看懂的东西)
将json格式的字符串变成对象

var jsonStr = '{"username":"jack"}'
console.log(JSON.parse(jsonStr).username)

5、localStorage(本地存储)


和cookie的区别

  • cookie的大小只有4kb 对应的localstorage有5M
  • cookie会随请求发送 localstorage不会随请求发送
  • cookie只能存储字符串 localstorage可以存储对应的图片以及视频的二进制
  • 存储的位置不一样的
  • cookie是可以过期的 localstorage不能过期

共同点

  • cookie和localstorage都是存储在浏览器上
  • 存储的内容的形式都是以字符串形式

6、案例:使用cookie实现购物车功能:     有以下商品, 点击加入购物车即可加入到购物车中(cookie中保存),     点击查看购物车, 进入另一个页面, 并显示之前加入购物车的商品.  

加入购物车的功能

<style>
        *{
            margin: 0;
            padding: 0;
        }
        #addGoodContent{
            border-radius: 5px;
            padding: 10px;
            border: 1px solid #000;
            line-height: 30px;
            width: 400px;
        }
        #addGoodContent>span{
            display: inline-block;
            width: 100px;
            letter-spacing: 5px;
        }
        #goodList{
            overflow: hidden;
            margin: 10px 50px;
        }
        .item{
            padding: 10px;
            float: left;
            width: 372px;
            height: 154px;
            overflow: hidden;
            color: #333;
            background-color: #f7f9fa;
            border: 1px solid #f7f9fa;
            -webkit-border-radius: 12px;
            -moz-border-radius: 12px;
            border-radius: 12px;
            cursor: pointer;
            display: flex;
            flex-direction: row;
        }
        .left{
            margin-right: 10px;
        }
        .left>img{
            width: 150px;
            height: 150px;
        }
        .right>h4{
            color: #333;
            font-size: 18px;
            line-height: 23px;
            margin: 5px 0;
        }
        .right>p{
            font-size: 14px;
            line-height: 22px;
            height: 80px;
        }
        .right span{
            color: red;
        }
    </style>
</head>
<body>
    <!-- 添加商品 -->
    <h2>添加商品</h2>
    <div id="addGoodContent">
        <span>商品名:</span> <input type="text"><br>
        <span>商品价格:</span> <input type="text"><br>
        <span>商品详情:</span> <br> <textarea type="text"></textarea><br>
        <span style="width: 150px;">商品的图片:</span> <input type="text"><br>
        <button id="save">添加商品</button>
    </div>
    <h2>商品列表</h2>
    <ul id="goodList">
       
    </ul>
    <a href="./购物车.html">查看购物车</a>
    <script>
        //加入商品的功能 cookie来存储的 (大小只有4kb)
        //localStorage 本地存储 他和cookie都是位于浏览器上 但是俩个的大小和特性不一样(5M)
        function addGood(goodName,goodPrice,info,imgUrl){
            //先取出商品列表本身有的数据
            var goodList = localStorage.getItem('goodList')?JSON.parse(localStorage.getItem('goodList')):[]
            //生成一个id
            var id = Date.now()+Math.random().toFixed(2)
            //初始化一个对象 存储对应的数据
            var good = {
                id,
                goodName,
                goodPrice,
                info,
                imgUrl
            }
            //加给localStroage
            goodList.push(good)
            addGoodToUl(good)
            localStorage.setItem("goodList",JSON.stringify(goodList))
        }
        //获取ul
        var ul = document.getElementById('goodList')
        randerGoodList()
        //给按钮添加事件
        document.querySelector('#save').onclick = function(){
            //获取所有输入的内容
            var inputs = document.querySelectorAll('input')
            var info = document.querySelector('textarea').value
            //调用添加的方法
            addGood(inputs[0].value,Number(inputs[1].value),info,inputs[2].value)
        }
        //商品列表渲染的功能
        function randerGoodList(){
            //根据localstroage里面存的数据 进行渲染
            var goodList = localStorage.getItem('goodList')?JSON.parse(localStorage.getItem('goodList')):[]
            //遍历这个数组进行渲染
            for(var good of goodList){
                addGoodToUl(good)
            }
        }
        function addGoodToUl(good){
            ul.innerHTML += `
                <li class="item">
                    <div class="left">
                        <img src="${good.imgUrl}" alt="">
                    </div>
                    <div class="right">
                        <h4>${good.goodName}</h4>
                        <p>${good.info}</p>
                        <div>
                            <span>¥<b>${good.goodPrice}</b></span>
                            <button onclick="addCar(${good.id})">加入购物车</button>
                        </div>
                    </div>
                </li>
                `
        }
        //加入购物车的功能
        function addCar(id){
            //通过id取出对应的元素
            var item = {}
            var goodList = localStorage.getItem('goodList')?JSON.parse(localStorage.getItem('goodList')):[]
            //遍历这个数组进行渲染
            for(var good of goodList){
              if(id == good.id){
                item = good
              }
            }
            //先取出之前购物车的东西
            var car = localStorage.getItem('car')?JSON.parse(localStorage.getItem('car')):[]
            //count 里面具备id 
            var flag = false //默认为没有
            //查找当前的car里面的内容是否具备这个id
            for(var good of car){
                if(good.id == item.id){  //如果有这个id count++
                    good.count++
                    flag = true
                }
            }
            if(!flag){ // 如果没有这个id count为1
                item.count = 1
                car.push(item)
            }
            //重新设置到localstorage里面去
            localStorage.setItem('car',JSON.stringify(car))
        }
    </script>
</body>

购物车

<style>
        .small{
            width: 100px;
        }
    </style>
</head>
<body>
    <table border="1px">
        <thead>
            <tr>
                <th><input type="checkbox" id="selectAll"> 全选</th>
                <th>
                    商品名
                </th>
                <th>
                    商品图片
                </th>
                <th>
                    商品详情
                </th>
                <th>
                    商品价格
                </th>
                <th>
                    商品个数
                </th>
                <th>
                    小计
                </th>
                <th>
                    操作
                </th>
            </tr>
        </thead>
        <tbody>
           
        </tbody>
        <tfoot>
           <tr>
             <td colspan="8" align="right"> 合计 ¥<span class="totalPrice">0</span></td>
           </tr>
        </tfoot>
    </table>
    <script>
        //购物车数据渲染
        // 数据显示在tbody里面
        var tbody = document.querySelector('tbody')
        //调用渲染方法
        randerList()
        function randerList(){
            var car = localStorage.getItem('car')?JSON.parse(localStorage.getItem('car')):[]
            //先要去localstorage拿对应的购物车数据 car
            //遍历
            for(var good of car){
                tbody.innerHTML += `
                <tr>
                    <td>
                        <input type="checkbox" class='check'>
                    </td>
                    <td>
                        ${good.goodName}
                    </td>
                    <td>
                        <img class="small" src="${good.imgUrl}" alt="">
                    </td>
                    <td>
                        ${good.info}
                    </td>
                    <td>
                        ¥<span>${good.goodPrice}</span>
                    </td>
                    <td>
                        <button class="btn" ${good.count==1?"disabled='disabled'":""} onclick='changeCount(${good.id})'>-</button>
                        <input type="number" value="${good.count}">
                        <button class="btn" onclick='changeCount(${good.id},true)' >+</button>
                    </td>
                    <td>
                        ¥<span>${good.goodPrice*good.count}</span>
                    </td>
                    <td>
                        <button onclick="rm(${good.id})">移除购物车</button>
                    </td>
                </tr>
                `
            }

        }
        //全选功能
        var selectAll = document.querySelector('#selectAll')
        var checks = document.querySelectorAll('.check')
        //给全选功能做操作
        selectAll.onclick = function(){
            for(var i=0;i<checks.length;i++){
               checks[i].checked = this.checked
            }
            computedPrice()
        }
        //给每个添加点击事件
        for(var i=0;i<checks.length;i++){
            checks[i].onclick = function(){
                computedPrice()
                if(isSelectAll()){
                    selectAll.checked = true
                }
            }
        }
        //判断是否全选的方法 如果全选返回true 如果不是返回false
        function isSelectAll(){
            var count = 0
            for(var i=0;i<checks.length;i++){
                if(checks[i].checked){
                    count++
                }
            }
           return count==checks.length
        }
        //计算价格的方法
        function computedPrice(){
                var prices = 0
                var car = localStorage.getItem('car')?JSON.parse(localStorage.getItem('car')):[]
                console.log(`car`, car);
                for(var i=0;i<checks.length;i++){
                    if(checks[i].checked){
                        prices +=(car[i].count * car[i].goodPrice)
                    }
                }
                //再给到totalPrice
                document.querySelector('.totalPrice').innerText = prices
        }
        //添加数量 //减少数量
        function changeCount(id,isAdd){
            var car = localStorage.getItem('car')?JSON.parse(localStorage.getItem('car')):[]
            //根据这个id获取对应的商品
            for(var good of car){
                if(id == good.id){
                    if(isAdd){
                        good.count++
                    }else{
                        good.count--
                    }
                }
            }
            //重新设置进去
            localStorage.setItem('car',JSON.stringify(car))
            //重新渲染
            // tbody.innerHTML = ""
            // randerList()
            location.reload()
        }
        //移除购物车的方法
        function rm(id){
            var car = localStorage.getItem('car')?JSON.parse(localStorage.getItem('car')):[]
            var index = -1
            //根据这个id获取对应的商品
            for(var i in car){
                if(id ==car[i].id){
                    index = i
                }
            }
            car.splice(index,1)
            //重新设置进去
            localStorage.setItem('car',JSON.stringify(car))
            //重新渲染
            location.reload()
        }
    </script>
</body>

 

posted @   木木子夕  阅读(431)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示