sindresorhus / query-string Goto Github PK
View Code? Open in Web Editor NEWParse and stringify URL query strings
License: MIT License
Parse and stringify URL query strings
License: MIT License
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
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.
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?
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
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
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?
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
.
https://github.com/sindresorhus/query-string/blob/master/index.js#L73
Why is it not being encoded? A small comment might help...
Is able to support a param for case insensitive?
As I do not see an option to reopen #30 I'm filing this as a new issue.
Please see my comment there #30 (comment) which gives an example of why it is important to not sort the values of the array.
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?
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?
Please provide typescript definitions
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 }
Using "query-string": "^4.3.4"
queryString.parse('?intended=sign-in)
returns
{
"?intended": "sign-in"
}
Unsafe usage of hasOwnProperty
means that parsing certain query strings will throw an error.
The following cases are also not working correctly:
qs.parse('__proto__');
qs.parse('__proto__&__proto__');
Object.create(null)
should fix the problem.
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
var qs = require('query-string');
// expected: {foo: 'c '}
qs.parse('foo=c++')
// => {foo: 'c++'}
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 !
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
Little edge case:
parse("?#foo=bar")
should equal {foo: "bar"}
, however it currently parses to {"#foo": "bar"}
(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.
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?
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
For example such usage will throw an error:
queryString.parse('?%');
queryString.parse('?key=%AF');
queryString.parse('#key%1=value');
What do you think about adding try catch
statement?
P.S.: https://github.com/ljharb/qs/blob/master/lib/utils.js#L78-L84
When there's only one value in array, it gives value without wrapped in array.
e.g.: queryString.parse('foo[]=bar', {arrayFormat: 'bracket'}) results in
{ foo: 'bar' }
but node.js parses same query string in
{ foo: ['bar'] }
https://github.com/koajs/qs#optional-parse-mode
strict
and first
are really useful.
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'} }
Why this new version is only for nodejs and not included for browsers. It broke my app when I bower updated the dependencies.
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.
parse("?&foo=bar")
should probably result in {"":"","foo":"bar"}
, but instead results in {"":null,"foo":"bar"}
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'}
Object {startDate: 1440355598853, endDate: 1440442008173, city: "bangalore", columns: Array[0]}
city=bangalore&&endDate=1440442008173&startDate=1440355598853
See the extra &
?
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.
Not an issue, more of a feature request:
Sometimes I find myself in the need of avoiding the encoding of a certain set of specific characters.
@sindresorhus do you think it'll be useful to add options to the stringify
method to specify which characters to exclude from encoding? Let me know and I could work on a PR for that.
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]}
What's the difference between query-string
and querystring
?
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?
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.
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]});
Why replace '+' with space in L20?
Breaks the parsing of this URL:
http://localhost:3000?startTime=2015-08-10T00:00:00+08:00&endTime=2015-08-20T04:00:00+08:00
> querystring.parse(location.search)
{
endTime: "2015-08-20T04:00:00 08:00",
startTime: "2015-08-10T00:00:00 08:00"
}
No longer a valid ISO-8601 timestamp :(
query-string currently parse all the query that is given to it.Is there a way to select allowed value only.
queryString.parse('foo[bar]=baz');
// => {
// => 'foo[bar]': 'baz'
// => }
// expected:
// => {
// => foo: {
// => bar: 'baz'
// => }
// => }
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.
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
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" }
I'm using v1 and just using it via the global namespace. is this still possible?
dont parse correct
he make object but not array
Doesn't work options for .stringify method.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.