【问题标题】:JSON from TypeScript and JSON.stringify来自 TypeScript 和 JSON.stringify 的 JSON
【发布时间】:2016-01-02 00:38:20
【问题描述】:

鉴于这个简化的场景:

export class LoginComponent{ 
   grant_type: string="password"; 
   jsonPayload: string; 

   Login(username, password){
      this.jsonPayload = JSON.stringify(username, password, this.grant_type);
   }
}

看起来 stringify 被 TypeScript 的“this”弄糊涂了。那么,我该如何制作格式正确的 JSON?

谢谢,

【问题讨论】:

    标签: json typescript


    【解决方案1】:

    stringify 接受三个参数,分别是:

    • 要字符串化的东西
    • 要使用的替换函数
    • 要使用的缩进

    您将一个非函数 (password) 作为第二个参数传递给它。

    您可能的意思是向它传递一个参数,一个对象到stringify

    this.jsonPayload = JSON.stringify({
        username,
        password, 
        grant_type: this.grant_type
    });
    

    或者如果您想明确说明所有三个,因为最后一个需要它:

    this.jsonPayload = JSON.stringify({
        username: username,
        password: password, 
        grant_type: this.grant_type
    });
    

    【讨论】:

    • 谢谢,T.J.!我现在有了格式良好的 JSON。只需要修复一个琐碎的预检错误...
    猜你喜欢
    • 2021-07-30
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    • 2020-09-03
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多