将json对象数据转换为x-www-form-urlencoded

Man*_*har 6 typescript angular

我希望将json对象转换为x-www-form-urlencoded如何在角度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);
    }
Run Code Online (Sandbox Code Playgroud)

Den*_*AUT 7

let o = { a:1, b:'2', c:true };
let s = new URLSearchParams(Object.entries(o)).toString();
console.log(s); 
Run Code Online (Sandbox Code Playgroud)

  • 您还可以直接将对象传递给 URLSearchParams,如下所示:`new URLSearchParams(o).toString()` (4认同)

Dee*_*pak 6

使用查询字符串,

npm 安装查询字符串

var querystring = require('querystring')

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

console.log(querystring.stringify(inputJson))
Run Code Online (Sandbox Code Playgroud)

这会将您的 json 转换为 application/x-www-form-urlencoded


小智 5

应用程序/ x-WWW窗体-urlencoded

控制名称和值将被转义.空格字符由+', and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by%HH' 替换,百分号和两个十六进制数字表示字符的ASCII代码.换行符表示为"CR LF"对(即%0D%0A'). The control names/values are listed in the order they appear in the document. The name is separated from the value 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("&");
Run Code Online (Sandbox Code Playgroud)

  • 这不是递归的. (3认同)