qs Library Guide

qs is a popular query parameters serialization and parsing library. The object may be an ordinary sequence into a query string, the query string or vice versa parsed into an object, and support complex nested. It is easy to get started:

Qs.parse('x[]=1') // {x: ['1']}
Qs.stringify({x: [1]}) // x%5B0%5D=1

Qs are two methods accepts an optional second parameter, allows us to configure the results, personally feel more useful are the following:

ignoreQueryPrefix和addQueryPrefix

ignoreQueryPrefix This parameter can help us to automatically filter out location.search front ❓, and then resolve, addQueryPrefixto true plus can give us the sequence of the time?

// 解析
Qs.parse('?x=1') // {?x: "1"}
Qs.parse('?x=1', {ignoreQueryPrefix: true}) //  {x: "1"}

// 序列化
Qs.stringify({x: "1"}) //  x=1
Qs.parse({x: "1"}, {addQueryPrefix: true}) //  ?x=1

Array parsing and serializing

There are several ways of array sequence: indices, brackets, repeat, comma, for controlling the generation of the format string. Consider the following example:

qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' })
// 'a[0]=b&a[1]=c'
qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' })
// 'a[]=b&a[]=c'
qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' })
// 'a=b&a=c'
qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'comma' })
// 'a=b,c'

The above four ways, the results obtained by the sequence of more and more streamlined, but when faced with a nested array, but it will lead to different levels of information loss, and the loss of more and more serious. Four ways to { a: [['b'], 'c'] }re-parse an example stringify:


qs.parse(qs.stringify({ a: [['b'], 'c'] }, { arrayFormat: 'indices' })) // { a: [['b'], 'c'] }
qs.parse(qs.stringify({ a: [['b'], 'c'] }, { arrayFormat: 'brackets' })) // {a: ["b", "c"]}
qs.parse(qs.stringify({ a: [['b'], 'c'] }, { arrayFormat: 'repeat' })) // {a: ["b", "c"]}
qs.parse(qs.stringify({ a: [['b'], 'c'] }, { arrayFormat: 'comma' })) // {a: "b,c"}

So when there are nested data using the best indicesmode, but fortunately this is the default mode.

delimiter

delimiter character which can be controlled as a separator, since the cookie format is used ;to separate, is a useful example for parsing cookie :

document.cookie // "_ga=GA1.2.806176131.1570244607; _jsuid=1335121594; _gid=GA1.2.1453554609.1575990858"
Qs.parse(document.cookie, {delimiter:'; '})

Digital type of analytical

As we saw in the first example, we have a sequence of numbers and then to restore, not to get a number, but a string:

Qs.parse(Qs.stringify({x:1})) // {x: '1'}

If you want to resolve it is still digital, can refer to this Issue , it is to write a custom decoder:

Qs.parse('x[0]=1', {
    decoder(str, defaultEncoder, charset, type) {
      if (/^(\d+|\d*\.\d+)$/.test(str)) {
        return parseFloat(str)
      }
      return str
    }
  })

This article finished

Guess you like

Origin www.cnblogs.com/imgss/p/12020058.html