简体   繁体   English

这个php json_encode的Node.js等效项是什么?

[英]What will be the Node.js equivalent of this php json_encode ?

I am looking for the Node.js of the following PHP Script: 我正在寻找以下PHP脚本的Node.js:

$SMA_APICall = "https://www.alphavantage.co/query?function=SMA&symbol=".$symbolValue."&interval=15min&time_period=10&series_type=close&apikey=R3MGTYHWHQ2LXMRS";
          $SMAresponse = file_get_contents($SMA_APICall);
          $jsonSMA = json_encode( $SMAresponse);

Here, I am trying to make a call to an API. 在这里,我正在尝试调用API。 The API call returns a json object. API调用返回一个json对象。 I want to repeat the same thing using Node js 我想使用Node js重复同样的事情

I believe what you're trying to do is making a request to an API and get the JSON data. 我相信您要尝试做的是向API发出请求并获取JSON数据。 Here's how you can do it with native Node.js module https 这是使用原生Node.js模块https

 const https = require('https');

 https.get(`https://www.alphavantage.co/query?function=SMA&symbol=${symbolValue}&interval=15min&time_period=10&series_type=close&apikey=R3MGTYHWHQ2LXMRS`, (resp) => {
  let data = '';

  resp.on('data', (chunk) => {
    data += chunk;
  });

  resp.on('end', () => {
    console.log(JSON.parse(data)); // JSON Data Here
  });

}).on("error", (err) => {
  console.log("Error: " + err.message);
});

There're several other ways you can do this with other simpler packages. 您还可以通过其他几种方法来使用其他更简单的软件包。 I highly recommend axios because it's cleaner and easier. 我强烈推荐axios因为它更干净,更容易。

The full examples please refer to this article 完整示例请参考本文

Take a look at the request library: https://github.com/request/request 看看request库: https : //github.com/request/request

var request = require('request');
var url = "https://www.alphavantage.co/query?function=SMA&symbol=" + symbolValue + "&interval=15min&time_period=10&series_type=close&apikey=R3MGTYHWHQ2LXMRS";
request(url, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    var jsonSMA = JSON.parse(body);
    // Continue code here
  }
});

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

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