Deserialize query string to JSON object

后端 未结 7 1224
感情败类
感情败类 2021-01-04 01:21

Tried to find how to make {foo:\"bar\"} from ?...&foo=bar&... but googled and got only to jQuery.params which does the opposit

7条回答
  •  说谎
    说谎 (楼主)
    2021-01-04 02:18

    for simple and flat query strings, something like this will do the trick

    const queryStringToObject = (queryString) => {
      let obj = {}
      if(queryString) {
        queryString.slice(1).split('&').map((item) => {
          const [ k, v ] = item.split('=')
          v ? obj[k] = v : null
        })
      }
      return obj
    }
    
    > queryStringToObject('?foo=bar&baz=buzz')
    { foo: 'bar', baz: 'buzz' }
    

提交回复
热议问题