Deserialize query string to JSON object

后端 未结 7 1226
感情败类
感情败类 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:05

    In modern browsers, you can also use Object.fromEntries which makes this even easier.

    function queryStringToObject(queryString) {
      const pairs = queryString.substring(1).split('&');
      // → ["foo=bar", "baz=buzz"]
    
      var array = pairs.map((el) => {
        const parts = el.split('=');
        return parts;
      });
      // → [["foo", "bar"], ["baz", "buzz"]]
    
      return Object.fromEntries(array);
      // → { "foo": "bar", "baz": "buzz" }
    }
    
    console.log(queryStringToObject('?foo=bar&baz=buzz'));


    The URLSearchParams interface can Interactive with the browsers URL search parameters. The browser support for URLSearchParams is pretty decent.

    For your case, it would be:

    console.log(
      Object.fromEntries(new URLSearchParams('foo=bar&baz=buzz'))
    );

提交回复
热议问题