简体   繁体   English

JSON字符串化JSON对象打字稿/角度

[英]JSON stringify json object typescript / angular

Hey I'm trying do stringify a JSON object or rather what i believe is a JSON object. 嘿,我正在尝试对JSON对象或我认为是JSON对象的字符串进行字符串化。 Below is my current code: 下面是我当前的代码:

const user: any = {
      Username: username,
      Password: password
};

console.log('Data: ' + JSON.stringify(user));

The console only prints out: 控制台仅打印出:

Data: {}

How can i modify my "JSON object" so it doesn't return empty? 如何修改我的“ JSON对象”,使其不返回空?

You'll get an empty object if both the username and password variables are undefined. 如果用户名和密码变量都未定义,则会得到一个空对象。 Angular won't create any keys that have undefined values. Angular不会创建任何具有未定义值的键。

The object the way you have it (without quotes) is referencing JavaScript variables and they may not contain actual values and not variable references: 您使用它的方式(不带引号)的对象正在引用JavaScript变量,并且它们可能不包含实际值,也不是变量引用:

{
  Username: usernameVariable,
  Password: passwordVariable
}

If you haven't defined those variables yet then they will have a value of "undefined". 如果尚未定义这些变量,则它们的值为“未定义”。

However, if you have quotes around the values then they will be actual values in the JSON object: 但是,如果您在值周围加上引号,那么它们将是JSON对象中的实际值:

{
  Username: "usernameValue",
  Password: "passwordValue"
}

I think that this would work... 我认为这会起作用...

<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>

<script>

var user = {
    Username: username, 
    Password: password
    };

var myJSON = JSON.stringify(user);
    document.getElementById("demo").innerHTML = myJSON;

</script>

</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM