在javascript中解析数组响应

时间:2017-11-16 20:12:16

标签: javascript arrays json parsing undefined

我正在处理API请求,其中我获取了一个http.response,它是一个包含一个json对象的数组。但是,当我尝试解析它或使用此代码将其字符串化时:

  var response = http.response;

try{
    var json = JSON.stringify(response);
    logInfo("status: " + json.status);
  } catch(e) { logInfo(e); }

...我得到这个日志anwser:status: undefined

如何定义值?该值来自我网页上的用户,可以更改。

这是我从请求中得到的回复:

[
{
"status": "DONE",
"plannedDeliveryDate": "2017-06-27",
"orderId": 2112312,
"userId": 123123
}
]

这是我的GET代码的其余部分:

loadLibrary("cus:json3.js"); 


var query = xtk.queryDef.create(
  <queryDef operation="select" schema={vars.targetSchema}>
    <select>
      <node expr="@userNumber"/>
    </select>
  </queryDef>
);

var res = query.ExecuteQuery();

//Buffer the auth key
var buffer = new MemoryBuffer();
buffer.fromString("username:password", "utf-8");

for each (var line in res) {

  var http = new HttpClientRequest();
  http.header["Authorization"] = "Basic " + buffer.toBase64(); //Basic Auth
  this.baseURL = "https://url..../data?user_id=" + line.@userNumber;
  http.url = this.baseURL;
  http.method = "GET"; //The GET request
  http.execute();

  var response = http.response;

try{
    var json = JSON.parse(response);
    logInfo("status: " + json[0].status);
  } catch(e) { logInfo(e); }
}

1 个答案:

答案 0 :(得分:-2)

要解析json,请使用

JSON.parse(response);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

JSON.stringify() does the opposite, it converts data into json