Query string module in node.js is used to provide utilities for parsing and formatting URL query strings. It also provide methods used for converting JSON to query string and
query string to JSON. We can require the query string module in the following way :
var qs = require('querystring');
//Name of the File : qs-parse.js
var qs = require('querystring');
var value_json = qs.parse('id=1&name=rj&name=njsera&tutorial=30daysofnode&creator=nodejsera')
console.log(value_json);
var value_json_2 = qs.parse('id%2&name%reij&name%njsera2&tutorial%30daysofnode&creator%nodejsera','&','%');
console.log("Changing the default 'eq' from '=' to '%'. An example is shown below:");
console.log(value_json_2);
var value_json_3 = qs.parse('id%3#name%emily#name%njsera3#tutorial%30daysofnode#creator%nodejsera','#','%');
console.log("Changing the default Separator 'sep' from '&' to '#'. An example is shown below:")
console.log(value_json_3);
>node qs-parse.js
{ id: '1',
name: [ 'rj', 'njsera' ],
tutorial: '30daysofnode',
creator: 'nodejsera' }
Changing the default 'eq' from '=' to '%'. An example is shown below:
{ id: '2',
name: [ 'reij', 'njsera2' ],
tutorial: '30daysofnode',
creator: 'nodejsera' }
Changing the default Separator 'sep' from '&' to '#'. An example is shown below:
{ id: '3',
name: [ 'emily', 'njsera3' ],
tutorial: '30daysofnode',
creator: 'nodejsera' }
//Name of the File : qs.stringify.js
var qs = require('querystring');
var value_json = qs.stringify({ id: 1, name: ['abc', 'njera'], tutorial: '30days of node', creator : 'nodejsera' });
console.log(value_json);
var value_json_2 = qs.stringify({ id: 2, name: ['def', 'njera2'], tutorial: '30days of node', creator : 'nodejsera' },';');
console.log("Changing the default 'sep' from '&' to ';'. An example is shown below:");
console.log(value_json_2);
var value_json_3 = qs.stringify( {id: 3, name: ['hij', 'njera3'], tutorial: '30days of node', creator : 'nodejsera' },';',':');
console.log("Changing the default 'eq' from '=' to ':'. An example is shown below:")
console.log(value_json_3);
>node qs-stringify.js
id=1&name=abc&name=njera&tutorial=30days%20of%20node&creator=nodejsera
Changing the default 'sep' from '&' to ';'. An example is shown below:
id=2;name=def;name=njera2;tutorial=30days%20of%20node;creator=nodejsera
Changing the default 'eq' from '=' to ':'. An example is shown below:
id:3;name:hij;name:njera3;tutorial:30days%20of%20node;creator:nodejsera
In this chapter of 30 days of node tutorial series, we learned about the basics of query strings , what are query strings,
.parse()
method of query strings and lastly .stringify()
method of query strings with working code snippets.