黄子涵

查漏补缺——说说JSON.parse方法

问题

如题所示

答案

相关源码:

export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, ' ') +
      '"}'
  )
}

这里返回的部分使用到JSON.parse,这个方法是啥意思呢?

JSON.parse()用法

JSON.parse()和JSON.stringify()

JSON.parse() 的坑!

根据上面,我们可以知道这个方法会将JSON字符串转换为JS对象,我们做一个实验吧:

var hzhJSONStr = '{"name": "黄子涵" ,"mother": "陈兰英" ,"brotherWife": "佘佳梓" }' 

console.log("将hzhJSONStr字符串转换为JS对象:");
console.log(JSON.parse(hzhJSONStr));
[Running] node "e:\HMV\JavaScript\JavaScript.js"
将hzhJSONStr字符串转换为JS对象:
{ name: '黄子涵', mother: '陈兰英', brotherWife: '佘佳梓' }

[Done] exited with code=0 in 0.234 seconds

实验验证了我们的想法。

posted @ 2022-07-02 16:12  黄子涵  阅读(141)  评论(0)    收藏  举报