GithubHelp home page GithubHelp logo

sindresorhus / query-string Goto Github PK

View Code? Open in Web Editor NEW
6.7K 32.0 446.0 252 KB

Parse and stringify URL query strings

License: MIT License

JavaScript 93.69% TypeScript 6.31%
query-string urlsearchparams url stringify parse npm-package

query-string's Introduction

query-string

Parse and stringify URL query strings





Install

npm install query-string

Warning

Remember the hyphen! Do not install the deprecated querystring package!

For browser usage, this package targets the latest version of Chrome, Firefox, and Safari.

Usage

import queryString from 'query-string';

console.log(location.search);
//=> '?foo=bar'

const parsed = queryString.parse(location.search);
console.log(parsed);
//=> {foo: 'bar'}

console.log(location.hash);
//=> '#token=bada55cafe'

const parsedHash = queryString.parse(location.hash);
console.log(parsedHash);
//=> {token: 'bada55cafe'}

parsed.foo = 'unicorn';
parsed.ilike = 'pizza';

const stringified = queryString.stringify(parsed);
//=> 'foo=unicorn&ilike=pizza'

location.search = stringified;
// note that `location.search` automatically prepends a question mark
console.log(location.search);
//=> '?foo=unicorn&ilike=pizza'

API

.parse(string, options?)

Parse a query string into an object. Leading ? or # are ignored, so you can pass location.search or location.hash directly.

The returned object is created with Object.create(null) and thus does not have a prototype.

options

Type: object

decode

Type: boolean
Default: true

Decode the keys and values. URL components are decoded with decode-uri-component.

arrayFormat

Type: string
Default: 'none'

  • 'bracket': Parse arrays with bracket representation:
import queryString from 'query-string';

queryString.parse('foo[]=1&foo[]=2&foo[]=3', {arrayFormat: 'bracket'});
//=> {foo: ['1', '2', '3']}
  • 'index': Parse arrays with index representation:
import queryString from 'query-string';

queryString.parse('foo[0]=1&foo[1]=2&foo[3]=3', {arrayFormat: 'index'});
//=> {foo: ['1', '2', '3']}
  • 'comma': Parse arrays with elements separated by comma:
import queryString from 'query-string';

queryString.parse('foo=1,2,3', {arrayFormat: 'comma'});
//=> {foo: ['1', '2', '3']}
  • 'separator': Parse arrays with elements separated by a custom character:
import queryString from 'query-string';

queryString.parse('foo=1|2|3', {arrayFormat: 'separator', arrayFormatSeparator: '|'});
//=> {foo: ['1', '2', '3']}
  • 'bracket-separator': Parse arrays (that are explicitly marked with brackets) with elements separated by a custom character:
import queryString from 'query-string';

queryString.parse('foo[]', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
//=> {foo: []}

queryString.parse('foo[]=', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
//=> {foo: ['']}

queryString.parse('foo[]=1', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
//=> {foo: ['1']}

queryString.parse('foo[]=1|2|3', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
//=> {foo: ['1', '2', '3']}

queryString.parse('foo[]=1||3|||6', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
//=> {foo: ['1', '', 3, '', '', '6']}

queryString.parse('foo[]=1|2|3&bar=fluffy&baz[]=4', {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
//=> {foo: ['1', '2', '3'], bar: 'fluffy', baz:['4']}
  • 'colon-list-separator': Parse arrays with parameter names that are explicitly marked with :list:
import queryString from 'query-string';

queryString.parse('foo:list=one&foo:list=two', {arrayFormat: 'colon-list-separator'});
//=> {foo: ['one', 'two']}
  • 'none': Parse arrays with elements using duplicate keys:
import queryString from 'query-string';

queryString.parse('foo=1&foo=2&foo=3');
//=> {foo: ['1', '2', '3']}
arrayFormatSeparator

Type: string
Default: ','

The character used to separate array elements when using {arrayFormat: 'separator'}.

sort

Type: Function | boolean
Default: true

Supports both Function as a custom sorting function or false to disable sorting.

parseNumbers

Type: boolean
Default: false

import queryString from 'query-string';

queryString.parse('foo=1', {parseNumbers: true});
//=> {foo: 1}

Parse the value as a number type instead of string type if it's a number.

parseBooleans

Type: boolean
Default: false

import queryString from 'query-string';

queryString.parse('foo=true', {parseBooleans: true});
//=> {foo: true}

Parse the value as a boolean type instead of string type if it's a boolean.

types

Type: object
Default: {}

Specify a pre-defined schema to be used when parsing values. The types specified will take precedence over options such as: parseNumber, parseBooleans, and arrayFormat.

Use this feature to override the type of a value. This can be useful when the type is ambiguous such as a phone number.

It is possible to provide a custom function as the parameter type. The parameter's value will equal the function's return value.

Supported Types:

  • 'string': Parse phoneNumber as a string (overriding the parseNumber option):
import queryString from 'query-string';

queryString.parse('?phoneNumber=%2B380951234567&id=1', {
	parseNumbers: true,
	types: {
		phoneNumber: 'string',
	}
});
//=> {phoneNumber: '+380951234567', id: 1}
  • 'number': Parse age as a number (even when parseNumber is false):
import queryString from 'query-string';

queryString.parse('?age=20&id=01234&zipcode=90210', {
	types: {
		age: 'number',
	}
});
//=> {age: 20, id: '01234', zipcode: '90210 }
  • 'string[]': Parse items as an array of strings (overriding the parseNumber option):
import queryString from 'query-string';

queryString.parse('?age=20&items=1%2C2%2C3', {
	parseNumber: true,
	types: {
		items: 'string[]',
	}
});
//=> {age: 20, items: ['1', '2', '3']}
  • 'number[]': Parse items as an array of numbers (even when parseNumber is false):
import queryString from 'query-string';

queryString.parse('?age=20&items=1%2C2%2C3', {
	types: {
		items: 'number[]',
	}
});
//=> {age: '20', items: [1, 2, 3]}
  • 'Function': Provide a custom function as the parameter type. The parameter's value will equal the function's return value.
import queryString from 'query-string';

queryString.parse('?age=20&id=01234&zipcode=90210', {
	types: {
		age: (value) => value * 2,
	}
});
//=> {age: 40, id: '01234', zipcode: '90210 }

NOTE: Array types (string[] and number[]) will have no effect if arrayFormat is set to none.

queryString.parse('ids=001%2C002%2C003&foods=apple%2Corange%2Cmango', {
	arrayFormat: 'none',
	types: {
		ids: 'number[]',
		foods: 'string[]',
	},
}
//=> {ids:'001,002,003', foods:'apple,orange,mango'}
Function
import queryString from 'query-string';

queryString.parse('?age=20&id=01234&zipcode=90210', {
	types: {
		age: (value) => value * 2,
	}
});
//=> {age: 40, id: '01234', zipcode: '90210 }

Parse the value as a boolean type instead of string type if it's a boolean.

.stringify(object, options?)

Stringify an object into a query string and sorting the keys.

options

Type: object

strict

Type: boolean
Default: true

Strictly encode URI components. It uses encodeURIComponent if set to false. You probably don't care about this option.

encode

Type: boolean
Default: true

URL encode the keys and values.

arrayFormat

Type: string
Default: 'none'

  • 'bracket': Serialize arrays using bracket representation:
import queryString from 'query-string';

queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'bracket'});
//=> 'foo[]=1&foo[]=2&foo[]=3'
  • 'index': Serialize arrays using index representation:
import queryString from 'query-string';

queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'index'});
//=> 'foo[0]=1&foo[1]=2&foo[2]=3'
  • 'comma': Serialize arrays by separating elements with comma:
import queryString from 'query-string';

queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'comma'});
//=> 'foo=1,2,3'

queryString.stringify({foo: [1, null, '']}, {arrayFormat: 'comma'});
//=> 'foo=1,,'
// Note that typing information for null values is lost
// and `.parse('foo=1,,')` would return `{foo: [1, '', '']}`.
  • 'separator': Serialize arrays by separating elements with a custom character:
import queryString from 'query-string';

queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'separator', arrayFormatSeparator: '|'});
//=> 'foo=1|2|3'
  • 'bracket-separator': Serialize arrays by explicitly post-fixing array names with brackets and separating elements with a custom character:
import queryString from 'query-string';

queryString.stringify({foo: []}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
//=> 'foo[]'

queryString.stringify({foo: ['']}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
//=> 'foo[]='

queryString.stringify({foo: [1]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
//=> 'foo[]=1'

queryString.stringify({foo: [1, 2, 3]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
//=> 'foo[]=1|2|3'

queryString.stringify({foo: [1, '', 3, null, null, 6]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
//=> 'foo[]=1||3|||6'

queryString.stringify({foo: [1, '', 3, null, null, 6]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|', skipNull: true});
//=> 'foo[]=1||3|6'

queryString.stringify({foo: [1, 2, 3], bar: 'fluffy', baz: [4]}, {arrayFormat: 'bracket-separator', arrayFormatSeparator: '|'});
//=> 'foo[]=1|2|3&bar=fluffy&baz[]=4'
  • 'colon-list-separator': Serialize arrays with parameter names that are explicitly marked with :list:
import queryString from 'query-string';

queryString.stringify({foo: ['one', 'two']}, {arrayFormat: 'colon-list-separator'});
//=> 'foo:list=one&foo:list=two'
  • 'none': Serialize arrays by using duplicate keys:
import queryString from 'query-string';

queryString.stringify({foo: [1, 2, 3]});
//=> 'foo=1&foo=2&foo=3'
arrayFormatSeparator

Type: string
Default: ','

The character used to separate array elements when using {arrayFormat: 'separator'}.

sort

Type: Function | boolean

Supports both Function as a custom sorting function or false to disable sorting.

import queryString from 'query-string';

const order = ['c', 'a', 'b'];

queryString.stringify({a: 1, b: 2, c: 3}, {
	sort: (a, b) => order.indexOf(a) - order.indexOf(b)
});
//=> 'c=3&a=1&b=2'
import queryString from 'query-string';

queryString.stringify({b: 1, c: 2, a: 3}, {sort: false});
//=> 'b=1&c=2&a=3'

If omitted, keys are sorted using Array#sort(), which means, converting them to strings and comparing strings in Unicode code point order.

skipNull

Skip keys with null as the value.

Note that keys with undefined as the value are always skipped.

Type: boolean
Default: false

import queryString from 'query-string';

queryString.stringify({a: 1, b: undefined, c: null, d: 4}, {
	skipNull: true
});
//=> 'a=1&d=4'
import queryString from 'query-string';

queryString.stringify({a: undefined, b: null}, {
	skipNull: true
});
//=> ''
skipEmptyString

Skip keys with an empty string as the value.

Type: boolean
Default: false

import queryString from 'query-string';

queryString.stringify({a: 1, b: '', c: '', d: 4}, {
	skipEmptyString: true
});
//=> 'a=1&d=4'
import queryString from 'query-string';

queryString.stringify({a: '', b: ''}, {
	skipEmptyString: true
});
//=> ''

.extract(string)

Extract a query string from a URL that can be passed into .parse().

Note: This behaviour can be changed with the skipNull option.

.parseUrl(string, options?)

Extract the URL and the query string as an object.

Returns an object with a url and query property.

If the parseFragmentIdentifier option is true, the object will also contain a fragmentIdentifier property.

import queryString from 'query-string';

queryString.parseUrl('https://foo.bar?foo=bar');
//=> {url: 'https://foo.bar', query: {foo: 'bar'}}

queryString.parseUrl('https://foo.bar?foo=bar#xyz', {parseFragmentIdentifier: true});
//=> {url: 'https://foo.bar', query: {foo: 'bar'}, fragmentIdentifier: 'xyz'}

options

Type: object

The options are the same as for .parse().

Extra options are as below.

parseFragmentIdentifier

Parse the fragment identifier from the URL.

Type: boolean
Default: false

import queryString from 'query-string';

queryString.parseUrl('https://foo.bar?foo=bar#xyz', {parseFragmentIdentifier: true});
//=> {url: 'https://foo.bar', query: {foo: 'bar'}, fragmentIdentifier: 'xyz'}

.stringifyUrl(object, options?)

Stringify an object into a URL with a query string and sorting the keys. The inverse of .parseUrl()

The options are the same as for .stringify().

Returns a string with the URL and a query string.

Query items in the query property overrides queries in the url property.

The fragmentIdentifier property overrides the fragment identifier in the url property.

queryString.stringifyUrl({url: 'https://foo.bar', query: {foo: 'bar'}});
//=> 'https://foo.bar?foo=bar'

queryString.stringifyUrl({url: 'https://foo.bar?foo=baz', query: {foo: 'bar'}});
//=> 'https://foo.bar?foo=bar'

queryString.stringifyUrl({
	url: 'https://foo.bar',
	query: {
		top: 'foo'
	},
	fragmentIdentifier: 'bar'
});
//=> 'https://foo.bar?top=foo#bar'

object

Type: object

url

Type: string

The URL to stringify.

query

Type: object

Query items to add to the URL.

.pick(url, keys, options?)

.pick(url, filter, options?)

Pick query parameters from a URL.

Returns a string with the new URL.

import queryString from 'query-string';

queryString.pick('https://foo.bar?foo=1&bar=2#hello', ['foo']);
//=> 'https://foo.bar?foo=1#hello'

queryString.pick('https://foo.bar?foo=1&bar=2#hello', (name, value) => value === 2, {parseNumbers: true});
//=> 'https://foo.bar?bar=2#hello'

.exclude(url, keys, options?)

.exclude(url, filter, options?)

Exclude query parameters from a URL.

Returns a string with the new URL.

import queryString from 'query-string';

queryString.exclude('https://foo.bar?foo=1&bar=2#hello', ['foo']);
//=> 'https://foo.bar?bar=2#hello'

queryString.exclude('https://foo.bar?foo=1&bar=2#hello', (name, value) => value === 2, {parseNumbers: true});
//=> 'https://foo.bar?foo=1#hello'

url

Type: string

The URL containing the query parameters to filter.

keys

Type: string[]

The names of the query parameters to filter based on the function used.

filter

Type: (key, value) => boolean

A filter predicate that will be provided the name of each query parameter and its value. The parseNumbers and parseBooleans options also affect value.

options

Type: object

Parse options and stringify options.

Nesting

This module intentionally doesn't support nesting as it's not spec'd and varies between implementations, which causes a lot of edge cases.

You're much better off just converting the object to a JSON string:

import queryString from 'query-string';

queryString.stringify({
	foo: 'bar',
	nested: JSON.stringify({
		unicorn: 'cake'
	})
});
//=> 'foo=bar&nested=%7B%22unicorn%22%3A%22cake%22%7D'

However, there is support for multiple instances of the same key:

import queryString from 'query-string';

queryString.parse('likes=cake&name=bob&likes=icecream');
//=> {likes: ['cake', 'icecream'], name: 'bob'}

queryString.stringify({color: ['taupe', 'chartreuse'], id: '515'});
//=> 'color=taupe&color=chartreuse&id=515'

Falsy values

Sometimes you want to unset a key, or maybe just make it present without assigning a value to it. Here is how falsy values are stringified:

import queryString from 'query-string';

queryString.stringify({foo: false});
//=> 'foo=false'

queryString.stringify({foo: null});
//=> 'foo'

queryString.stringify({foo: undefined});
//=> ''

FAQ

Why is it parsing + as a space?

See this answer.

query-string's People

Contributors

bug-brain avatar cheqianxiao avatar doochik avatar dubzzz avatar esetnik avatar felixoi avatar gangsthub avatar jarrku avatar kevva avatar laat avatar moredip avatar neykov avatar padupuy avatar qstrahl avatar rapzo avatar rcoy-v avatar richienb avatar rocktimsaikia avatar rreusser avatar samverschueren avatar saromanov avatar scottenock avatar seanparmelee avatar sindresorhus avatar talbenmoshe avatar tlhunter avatar tpict avatar tranvansang avatar viczhuravlev avatar yaodingyd avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

query-string's Issues

Not handling multiple inputs of the same name

Given the following location.search provided by submitting via the submit event (or serializing) a form with one search input with name="search" and value="John", and three checked checkbox controls with name="brand":

?search=John&brand=AK&brand=ALA&brand=AE&brand=ARB

The parse method of this library returns:

{search: "John", brand: "ARB"}

Instead, I would expect something similar to jgallen23/querystring:

{search: "John", brand: Array[4]}

Firefox – stops parsing on equal sign

In Firefox, given the hash in the URL is #code=var%20foo%20%3D%20'bar'%3B:

var queryString = require('query-string');
queryString.parse(location.hash);

Output:

{code: 'var foo '}

Seems to stop parsing when it encounters an equal sign. Chrome works fine.

add method to get query string from url

For convenience, it would be nice to have a method that can pluck the query string from a url:

var qs = require("query-string");
var url = "http://some.url/with?a=few&query=params";
var query = qs.getQuery(url); // "?a=few&query=params"
qs.parse(query); // { a : "few", query : "params" }

parse() with arrayFormat bracket bug?

I'm trying to do the following:

const obj = qs.parse('a[]=value&a[]=value2&b=1234', { arrayFormat: 'bracket' })

I was expecting:
{
   a: ['value', 'value2'],
   b: 1234
}

But I actually get:

{
   a[]: ['value', 'value2'],
   b: 1234
}

Compare this to the behavior without adding in the non-array value:

// removed b
const obj = qs.parse('a[]=value&a[]=value2', { arrayFormat: 'bracket' })

Result:

{
   a: ['value', 'value2']
}

I also noticed the test cases for the parse function does not cover the first situation as well. Potential bug?

Breaks in Firefox

Thanks to https://bugzilla.mozilla.org/show_bug.cgi?id=483304, this module breaks if you use window.location.hash directly.

It's not really your fault, but, it is important to note this module is unsafe to use in the suggested way.

Perhaps check if the decodeURIComponent actually changes anything first, and if it doesn't, assume it is already decoded?

edit: For that to work though you'd have to stipulate (pre-decoded) base 64 keys would be unsafe (as you'd only be able to split on the first =)

edit2: Or just suggest this

IE8 and String.prototype.trim

(I know, I know) Unfortunately we have to support IE8 for a little while longer over here. String.prototype.trim isn't a thing in IE8. While I dislike munging with prototypes of native classes, this would be a simple addition:

if (!String.prototype.trim) {
  (function() {
    // Make sure we trim BOM and NBSP
    var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
    String.prototype.trim = function() {
      return this.replace(rtrim, '');
    };
  })();
}

Or alternatively, making that a private scope function would work as well.

Is strict-uri-encode really necessary?

I am using https://github.com/Sage/jsurl to efficiently encode JSON objects in the search string, and it uses the looser URI encoding range used by browsers, including the ' character.

I also use rackt/history which uses query-string, which converts ' to %27, which grows my urls, which makes me sad. Is there a reason the strict URI range should be used?

base64 in url

Hi,
http://localhost:8000/activate?appl_id=3298&access_key=tYq3O1GMZR+MP6fKvcdobQ/IQfapaw9wV3oa2t5SKxA=
the access_key is a base64 string, which contains + , and it gets replaced by space in source code:

	var parts = param.replace(/\+/g, ' ').split('=');

why do we need to replace + to space? the urlEncoded space is %20 isn't it?

Arrays should not be sorted

Arrays should be serialized in the given order and not by sorting their values. This leads to unexpected surprises for APIs which are sensitive to ordering, e.g.

Example:

queryString.stringify({
    routing: 'car',
    route: ["London", "Berlin"],
});

should produce
routing=car&route=London&route=Berlin instead of the current resultrouting=car&route=Berlin&route=London

Browser support

Why this new version is only for nodejs and not included for browsers. It broke my app when I bower updated the dependencies.

Parse error with string start /?

With string start with /? like http://example.com/?page=1, result return

queryString.parse('http://example.com/?page=1');
{ 'http://example.com/?page': '1' }
queryString.parse('/?page=1');
{'/?page':'1'}

q

stringify not working correctly,

When I am trying to stringify my object getting this
queryString.stringify({foo: [1,2,3]}, {arrayFormat: 'bracket'});
getting output foo=1[object Object]foo=2[object Object]foo=3
expected out put foo[]=1&foo[]=2&foo[]=3

Upgrade guide or change log

Is there an upgrade guide or change log that I'm missing? I'm looking for the steps to upgrade from 3.0.3 to the latest 4.2.2 release.

Don't mutate query params that are arrays when sorting their values before uri encoding

In stringify(obj), properties on the query params object that are of type Array are currently being sorted with Array.prototype.sort(), which mutates the original array. This causes errors for applications that use immutable data if the query params object being sent to stringify is frozen (or even if the object is not actually frozen, it can cause an undesired mutation of state). It may cause problems for other applications as well, if they are using the same object elsewhere and are not expecting the array order to be mutated.

This could be solved by just creating a new array in the sort rather than performing the sort on the original array. Happy to submit a pull request with a proposed fix if that would be helpful.

disable sorting

How to disable sorting before encoding?


data = { pair: 'USD_RUB',
  quantity: 234,
  price: 59.4,
  type: 'buy'
 }

query-string.stringify(data) -> pair=USD_RUB&price=59.4&quantity=234&type=buy

and I need so:
pair=USD_RUB&quantity=234&price=59.4&type=buy

please help

Incorrect handling of arrays?

Currently if query-string encounters an array it encodes it without brackets:

> require('query-string').stringify({foo: ['bar', 'baz']})
'foo=bar&foo=baz'

However that seems to go against the default browser behavior or one of other languages such as PHP. Shouldn't it be foo[]=bar&foo[]=baz?

I know this is kind of a grey area of the RFC but that struck me as odd, is this intended?

.stringify

Doesn't work options for .stringify method.

in arrays passed to stringify, `null` the same as string `"null"`

I'm not sure if this is a bug; maybe it's intended or unspecified behavior. Within an array, null is the same as the string "null".

var params = {'a': null, 'b': [null, 123]};
require('querystring').stringify(params);
// Node core: "a=&b=&b=123"
require('query-string').stringify(params);
// query-string: "a&b=123&b=null"

Here's my rationale:

var qs = require('query-string');
// If these are equivalent:
qs.stringify({a: 123}) === qs.stringify({a: [123]});
// These should be as well?
qs.stringify({a: null}) === qs.stringify({a: [null]});

stringify breaks on empty array

Object {startDate: 1440355598853, endDate: 1440442008173, city: "bangalore", columns: Array[0]}
city=bangalore&&endDate=1440442008173&startDate=1440355598853

See the extra & ?

support for nested attributes

Hey. Any plans to support nested attributes? Parser returns this:

{ a1: '111', a2: '222', 'user[name]': 'me' }

It should be

{ a1: '111', a2: '222', user: { name: 'me'} }

result from `parse` no longer has `hasOwnProperty` method

in 3.0.1, parse had the following behavior:

> qs.parse('my-param=my-val')
{ 'my-param': 'my-val' }
> qs.parse('my-param=my-val').hasOwnProperty
[Function: hasOwnProperty]
> qs.parse('h=j').hasOwnProperty
[Function: hasOwnProperty]
> qs.parse('').hasOwnProperty
[Function: hasOwnProperty]

in 3.0.2, the object returned no longer has the hasOwnProperty method:

> qs.parse('hbud-fixture=not-logged-in')
{ 'hbud-fixture': 'not-logged-in' }
> qs.parse('hbud-fixture=not-logged-in').hasOwnProperty
undefined
> qs.parse('hbudfixture=not-logged-in').hasOwnProperty
undefined
> qs.parse('hbudfixture=notloggedin').hasOwnProperty
undefined
> qs.parse('').hasOwnProperty
[Function: hasOwnProperty]
> qs.parse('h=j').hasOwnProperty
undefined

I am unsure whether this was considered part of the API, but some consumers rely on the behavior - https://github.com/mjackson/history/blob/master/modules/useQueries.js#L13

URIError: malformed URI sequence

When you reload a page with a URL having the form '?q=%' an error occurs URIError: malformed URI sequence

Solution:

try { val = val === undefined ? null : decodeURIComponent(val); } catch (e) { val = null; }

Is it correct?

Support to object nesting

The module doesn't support object tree. Example:

var foo = {
    filter: {
        brand: [
            'a',
            'b'
            ]
    },
    size: 42
};
queryString.stringify(foo);

should generate
filter%5Bbrand%5D%5B0%5D=a&filter%5Bbrand%5D%5B1%5D=b&size=42
or
filter[brand][0]=a&filter[brand][1]=b&size=42

but the output was
filter=%5Bobject%20Object%5D&size=42 or filter=[object Object]&size=42

I need something that can parse anything to queryString, like PHP's http_build_query and parse_str

stringify method doesn't return a `?`

This is the stringify example on the documentation :

location.search = queryString.stringify(parsed);

console.log(location.search);
//=> '?foo=unicorn&ilike=pizza'

You can notice the ? at the begining, but in reality, it doesn't return it. I wanted to make a pull request, but I wasn't sure of what should be changed , the documentation or the code !

Doesn't support nesting

queryString.parse('foo[bar]=baz');
// => {
// =>   'foo[bar]': 'baz'
// => }

// expected:
// => {
// =>   foo: {
// =>     bar: 'baz'
// =>   }
// => } 

Array need in the same format with comma separated

Suppose,
let path = {
pathname : [ 'path1'],
direction : ['dir1', 'dir2','dir3'],
stops: ['stop1','stop2'],
};

queryString.stringify(path);
==> &path={"pathname":["path1"],"direction":["dir1","dir2","dir3"],"stops":["stop1","stop2"]}

Is this possible. Thanks.

IE8 doesn't support Object.keys()

Consider putting a polyfill in the code:

if (!Object.keys) {
  Object.keys = function(obj) {
    var keys = [];

    for (var i in obj) {
      if (obj.hasOwnProperty(i)) {
        keys.push(i);
      }
    }

    return keys;
  };
}

I know, I know... Who the hell still supports IE8 right?

stringify array as comma separated values

Hello there,

it could very nice to have ability to do something like this :

const obj = {foo: [1,2,3]};
queryString.stringify(obj, {arrayFormat: 'comma'})

And the result of this method will be: foo=1,2,3.

Expressing query params as arrays with a single element

Hi, before history switched from qs I used array-value params:

{ // query object
  paramName: ['firstValue']
}

Which was serialized to:

?paramName[]=firstValue

So when it was re-parsed we'd end up with the same query object. It doesn't look like the query-string stringifier has a way to express array values with a single element, as a result the re-parsed query object is different than the original query object:

{
  paramName: 'firstValue'
}

Is there any way to achieve transitive stringify/parse behavior with this lib or is that out of scope? I can write my own custom parser/stringifier if needed.

multi level bracket notation

Hi, how can I deal with situations like:

queryString.parse('?obj[child][prop1]=11&obj[child][prop2]=22')

//yield:
{
  "obj[child][prop1]":"11"
  "obj[child][prop2]":"22"
}

// instead:
{
  obj:{
    child: {
      prop1: "11"
      prop2: "22"
    }
  }
}

arrayFormat: 'index' doesn't help in this situation. Any help appreciated :) ty

Should handle querystrings in case-insensitive manner

You never know if a user or some other system is going to provide a querystring parameter in the same case that you expect. There should be an option that allows you to specify case insensitive handling and if this option is on (in fact it should be the default) then all querystring parameters come in as lowercase (properties or key names)

e.g

http;//www.my.website.com/somepage.html?QuerYpaRam1=somevalue

Result

{ queryparam1: somevalue }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.