JSON和数据存储的学习

128 阅读2分钟

JSON和数据存储的学习

JSON表示方式

[
  "hahaha",
  {
    "name": "Fhup",
    "age": 18,
    "height": 1.88,
    "hobbies": {
      "lilei": "nasketball"
    }
  },
  [
    {
      "name": "xxx",
      "age": 18
    },
    {
      "name": "yyy",
      "age": "21"
    }
  ]
]

JSON的序列化需求

const obj = {
  name: 'Fhup',
  age: 18,
  height: 1.88
}

// js对象与json的转换
const jsonStr = JSON.stringify(obj) 
console.log(JSON.parse(jsonStr))

// 将对象数据存储localStorage,需要存储字符串
localStorage.setItem('obj', JSON.stringify(obj)) // 序列化

console.log(JSON.parse(localStorage.getItem('obj'))) // 解析

序列化stringify细节

const obj = {
  name: 'Fhup',
  age: 18,
  height: 1.88,
  // toJSON(){
  //   return 'aaa'
  // }
}

// 将对象转为json字符串
// 1.直接转换
const jsonStr1 = JSON.stringify(obj)
console.log(jsonStr1);

// 2.stringify第二个参数 replacer
// 2.1 传入数组: 设置哪些需要转换
const jsonStr2 = JSON.stringify(obj, ['name', 'age'])
console.log(jsonStr2);

// 2.2 传入回调函数
const jsonStr3 = JSON.stringify(obj, (key, value)=>{
  if(key === 'age') {
    value+=1
  }
  return value
})
console.log(jsonStr3);

// 3.stringify 第三参数 space: 转换之后的缩进(美化代码)
const jsonStr4 = JSON.stringify(obj, null, "---")
console.log(jsonStr4);

// 4. obj有toJSON(),直接取返回值.

解析parse细节

const jsonStr = '{"name":"Fhup","age":18,"height":1.88}'

// 1.直接转换
const info1 = JSON.parse(jsonStr)
console.log(info1);
// 2.参数2的回调对解析的对象进行拦截处理
const info2 = JSON.parse(jsonStr, (key, value) => {
  if(key === 'age') {
    value-=10
  }
  return value
})
console.log(info2);

利用JSON序列化深拷贝

const info={name:'Fhup',age:18,friend:{name:'james'}}

// Object.assign
/// 展开运算符 [...xxx] {...xxx} ,也是浅拷贝
const newInfo = Object.assign({}, info) // 浅拷贝
console.log(newInfo)

info.friend.name = 'xxxxxx'
console.log(newInfo)


// 深拷贝: JSON.stringify() / parse()
/// 缺点: 不能对函数进行转换,遇到函数直接跳过.


Storage工具类的封装

class Cache {
  constructor(isLocal = true) {
    this.storage = isLocal ? localStorage : sessionStorage
  }
  setCache(key, value) {
    if(value){
      this.storage.setItem(key, JSON.stringify(value))
    }
  }
  getCache(key) {
    const value = this.storage.getItem(key)
    if(value){
      return JSON.parse(value)
    }
  }
  removeCache(key) {
    this.storage.removeItem(key)
  }
  clearCache() {
    this.storage.clear()
  }

  key(index) {
    return this.storage.key(index)
  }
  // 将属性封装为方法
  length() {
    return this.storage.length
  }
}

const localCache = new Cache()
const sessionCache = new Cache(false)

export{
  localCache,
  sessionCache
}

indexedDB数据库

// 1.与数据库建立连接
const request = indexedDB.open('Fhup') //有打开,没就新建
request.onerror = function(err) {
  console.log('打开失败!');
}
let db = null
request.onsuccess = function(event) {
  db = event.target.result
}
// 第一次打开 / 或者版本发生升级
request.onupgradeneeded = function(event) {
  const db = event.target.result

  // 创建存储对象
  db.createObjectStore('users', { keyPath: 'id' }) // 主键为id
}

class User {
  constructor(id, name, age) {
    this.id = id
    this.name = name
    this.age = age
  }
}

const users = [
  new User(101, 'Fhup', 18),
  new User(102, 'kobe', 40),
  new User(103, 'lilei', 20)
]

const btns = document.querySelectorAll('button')
const text = document.querySelector('p')

for(let i = 0; i < btns.length; i++) {
  btns[i].addEventListener('click', ()=>{
    const transaction = db.transaction(['users'], 'readwrite') // 事务
    const store = transaction.objectStore('users') // 获取存储对象
    switch (i) {
      case 0:
        for(const user of users) {
          const insertRequest = store.add(user)
          insertRequest.onsuccess = function() {
            console.log(`${user.name}插入成功`);
          }
          insertRequest.onerror = function(event) {
            console.log('已经插入,请勿再次插入')
          }
        }
        
        transaction.oncomplete = function() {
          text.innerHTML = '添加操作全部完成'
        }
        break;
      case 1:
        // 1.查询方式一: 查询单个,根据主键查询
        // const request = store.get(001)
        // request.onsuccess = function(event) {
        //   console.log(event.target.result);
        //   text.innerHTML = '查询成功!'
        // }
        // 2.查询方式二: 
        const queryRequest = store.openCursor()
        queryRequest.onsuccess = function(event) {
          const cursor = event.target.result

          // if(cursor) {
          //   console.log(cursor.key, cursor.value);
          //   cursor.continue()
          // }else {
          //   text.innerHTML = '查询成功!'
          // }

          if(cursor.key === 103){
            console.log(cursor.key, cursor.value);
            text.innerHTML = '查询103成功!'
          }else{
            console.log('--------');
            cursor.continue()
          }
        }
        break;
      case 2:
        const deleteRequest = store.openCursor()
        deleteRequest.onsuccess = function(event) {
          const cursor = event.target.result
          if(cursor.key === 102){
            cursor.delete()
            text.innerHTML = '删除102记录成功'
          }else{
            cursor.continue()
          }
        }
        break;
      case 3:
        const updateRequest = store.openCursor()
        updateRequest.onsuccess = function(event) {
          const cursor = event.target.result
          if(cursor.key === 103){
            const value = cursor.value
            value.name = 'xxxxxx'
            cursor.update(value)
            text.innerHTML = '修改103的名字为xxxxxx,成功'
          }else{
            cursor.continue()
          }
        }
        break;
      default:
        text.innerHTML = '错误'
        break;
    }
  })
}