简体   繁体   English

如何将 JSON 中的值分配给 javascript 中的变量

[英]How to assign a value from JSON to a variable in javascript

I am using the CheckPoint API in my web app and I am trying to store the "sid" in a variable.我在我的 web 应用程序中使用 CheckPoint API,我试图将“sid”存储在变量中。 How can I do this?我怎样才能做到这一点? Below is the code snippet that I use to login下面是我用来登录的代码片段

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({ user: "Licenta2020", password: "Licenta2020" });

var requestOptions = {
  method: "POST",
  headers: myHeaders,
  body: raw,
  redirect: "follow",
};
fetch("https://192.168.100.100/web_api/v1.6/login", requestOptions)
  .then((response) => response.text())
  .then((result) => {
    console.log(result);
  })
  .catch((error) => console.log("error", error));

And here is the result of this request, I want to take the sid value and assign to a variable so I can use it later on for other requests.这是此请求的结果,我想获取 sid 值并分配给一个变量,以便以后可以将其用于其他请求。

{
  "uid" : "4a587f4b-6a0a-4e0f-a1f4-cb99b19657dd",
  "sid" : "ite95YKJ7gmV-7s4YJbHIeAke9ODoklA5Z1yVHriRkA",
  "url" : "https://192.168.100.100:443/web_api/v1.6",
  "session-timeout" : 600,
  "last-login-was-at" : {
    "posix" : 1591398092564,
    "iso-8601" : "2020-06-06T02:01+0300"
  },
  "disk-space-message" : "Partition /var/log has: 1354 MB of free space and it's lower than required: 2000 MB\n",
  "api-server-version" : "1.6"
}

Tried this code snippet too也试过这个代码片段

.then((result) => {
    let sid = result.sid;
    console.log(result);
    console.log(sid);
  })

you are returning text in promise as .text() instead use .json();您将 promise 中的文本作为.text()返回,而不是使用 .json .json();

that's because .json() automatically parses to json for you.那是因为 .json .json()会自动为您解析为 json。 so after that you could continue to use result["sid"] to get desired output所以在那之后你可以继续使用result["sid"]来获得所需的 output

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

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