Parsing and Serializing Query Strings and JSON in Node.js with qs and JSON APIs
qs.parse(): parse a query string into a object
Transforms the query portion of a URL (the part after the ?) into a plain JavaScript object. Only pass the query string itself, not the entire URL.
const qs = require('qs');
const fullUrl = 'https://api.example.com/report?method=query_sql_dataset_data&projectId=85&appToken=7d22e38e-5717-11e7-907b-a6006ad3dba0';
const queryOnly = new URL(fullUrl).search.slice(1); // remove leading '?'
const params = qs.parse(queryOnly);
console.log(params);
Console output:
{
method: 'query_sql_dataset_data',
projectId: '85',
appToken: '7d22e38e-5717-11e7-907b-a6006ad3dba0'
}
qs.stringify(): serialize an object into a query string
Conevrts a JavaScript object into a URL-encoded query string suitalbe for use in a URL. Special characetrs and spaces are percent-encoded.
const qs = require('qs');
const payload = {
method: 'query_sql_dataset_data',
projectId: '85',
appToken: '7d22e38e-5717-11e7-907b-a6006ad3dba0',
datasetId: ' 12564701' // leading space will be encoded
};
const queryString = qs.stringify(payload);
console.log(queryString);
Console output:
method=query_sql_dataset_data&projectId=85&appToken=7d22e38e-5717-11e7-907b-a6006ad3dba0&datasetId=%2012564701
JSON.parse(): convert JSON text to a JavaScript value
Parses a JSON-formatted string in to a JavaScript value (object, array, etc.). JSON requires double quotes around property names and string values.
const jsonText = '[{"field":"thedate","v1":"20170102"},{"field":"rev_type","v1":"Big Data Income"},{"field":"thismonth","v1":"201708"},{"field":"nextmonth","v1":"201709"},{"field":"depart_type","v1":"leader"},{"field":"admin_emp_id","v1":"role"}]';
const data = JSON.parse(jsonText);
console.log(data);
Console output:
[
{ field: 'thedate', v1: '20170102' },
{ field: 'rev_type', v1: 'Big Data Income' },
{ field: 'thismonth', v1: '201708' },
{ field: 'nextmonth', v1: '201709' },
{ field: 'depart_type', v1: 'leader' },
{ field: 'admin_emp_id', v1: 'role' }
]
JSON.stringify(): convert a JavaScript value to JSON text
Serializes a JavaScript value into a JSON string. The result uses double quotes for property names and string values.
const rows = [
{ field: 'thedate', v1: '20170102' },
{ field: 'rev_type', v1: 'Big Data Income' },
{ field: 'thismonth', v1: '201708' },
{ field: 'nextmonth', v1: '201709' },
{ field: 'depart_type', v1: 'leader' },
{ field: 'admin_emp_id', v1: 'role' }
];
const jsonOut = JSON.stringify(rows);
console.log(jsonOut);
Console output:
[{"field":"thedate","v1":"20170102"},{"field":"rev_type","v1":"Big Data Income"},{"field":"thismonth","v1":"201708"},{"field":"nextmonth","v1":"201709"},{"field":"depart_type","v1":"leader"},{"field":"admin_emp_id","v1":"role"}]