Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert JS object data to x-www-form-urlencoded

I wish to convert a JS object into x-www-form-urlencoded. How can I achieve this in angular 2?

export class Compentency {
  competencies : number[];
}
postData() {
        let array =  [1, 2, 3];
        this.comp.competencies = array;
        let  headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
        let options = new RequestOptions({ headers: headers, method: 'post' });
        return this.http.post(this.postUrl, JSON.stringify(this.comp), options)
        .map(res => res.json().data.competencies)
        .catch(this.handleError);
    }
like image 665
Manohar Avatar asked Sep 30 '16 07:09

Manohar


People also ask

How do you send an object in X-www-form-Urlencoded?

To use the x-www-form-urlencoded type in Postman, we need to select the radio button with the same name within the request's body tab. As already mentioned, the request consists of the key-value pairs. Postman will encode the data before sending it to the server. Additionally, it will encode both the key and the value.

How do you convert an object in JavaScript?

Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');

What transforms a JavaScript object into a JSON string?

The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.


2 Answers

let o = { a:1, b:'2', c:true };
let s = new URLSearchParams(Object.entries(o)).toString();
console.log(s); 
like image 79
Denis TRUFFAUT Avatar answered Sep 29 '22 20:09

Denis TRUFFAUT


Assume have an object named postdata as below:

const postdata = {
  'a':1,
  'b':2,
  'c':3
};

and, you want convert it into x-www-form-urlencoded format, like: a=1&b=2&c=3

with URLSearchParams it's very easy to do it.

const rawData = new URLSearchParams(Object.keys(postdata).map(key=>[key,postdata[key]]));
console.log(rawData.toString());//a=1&b=2&c=3
like image 28
朱小江 Avatar answered Sep 29 '22 21:09

朱小江