Convert json object data to x-www-form-urlencoded

I want to convert a json object to x-www-form-urlencoded. How can I achieve this in angular 2 final version

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);
    }
+4
source share
2 answers

application / x-www-form-urlencoded

Control names and values ​​are escaped. Space characters are replaced with +', and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by% HH ', a percent sign, and two hexadecimal digits representing the ASCII character code. Line breaks are represented as pairs of "CR LF" (ie %0D%0A'). The control names/values are listed in the order they appear in the document. The name is separated from the value by= ', and name / value pairs are separated by "&".

JSON. JSON : encodeURIComponent (propertyKey) + "=" + encodeURIComponent (propertyValue) . .

   var str = [];
    for (var key in obj) {
         if (obj.hasOwnProperty(key)) {
               str.push(encodeURIComponent(key) + "=" + encodeURIComponent(obj[key]))                  
               console.log(key + " -> " + obj[key]);
         }
    }
    return str.join("&");
+4

querystring,

npm install querystring

var querystring = require('querystring')

var inputJson = {
   name: "Asdf",
    age: 23
}

console.log(querystring.stringify(inputJson))

json application/x-www-form-urlencoded

+1

Source: https://habr.com/ru/post/1656318/


All Articles