带有json的Node.JS和Object.Keys

时间:2021-09-21 22:01:58

The Code:

代码:

(URL is a working rest api that passes json data)

(URL是传递json数据的工作休息api)

var request = require('request');


var username = "user";
var password = "pass";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");



var url = "URL";

request(
    {
        method: "GET",
        url : url
    },
    function (error, response, data) {

          console.log(data);

          var initial_index = Object.keys(data.sites)[0];
          var product_index = Object.keys(data.sites[initial_index].products)[0];

          var order_id = data.purchase_id;
          var title = data.sites[initial_index].products[product_index].title;
          var content = data.sites[initial_index].products[product_index].description;
          var image = data.sites[initial_index].products[product_index].image;
          var total_price = data.sites[initial_index].prices.final_price;
          var quantity = data.sites[initial_index].products[product_index].input_fields.quantity;
          var sold_by = data.sites[initial_index].info.name;
          var order_status = data.sites[initial_index].status;




          var datatwo = {
            "status": "published",
            "order_id": order_id,
            "title": title,
            "content": content,
            "image": image,
            "final_price": total_price,
            "quantity": quantity,  
            "sold_by": sold_by,  
            "order_status": order_status
          };      


    }
);

I receive this error when running the code. How can it be resolved?

运行代码时收到此错误。怎么解决?

var initial_index = Object.keys(data.sites)[0];
                                 ^

TypeError: Cannot convert undefined or null to object

1 个解决方案

#1


2  

You're not parsing the JSON (which is text) you get back. Add this at the top of your request callback:

你没有解析你得到的JSON(文本)。在请求回调的顶部添加此项:

data = JSON.parse(data);

E.g.:

例如。:

request(
    {
        method: "GET",
        url : url
    },
    function (error, response, data) {
          data = JSON.parse(data);

          var initial_index = Object.keys(data.sites)[0];

          // ...

One you've parsed it, you'll have an object tree you can traverse.

你已经解析了它,你将拥有一个可以遍历的对象树。

#1


2  

You're not parsing the JSON (which is text) you get back. Add this at the top of your request callback:

你没有解析你得到的JSON(文本)。在请求回调的顶部添加此项:

data = JSON.parse(data);

E.g.:

例如。:

request(
    {
        method: "GET",
        url : url
    },
    function (error, response, data) {
          data = JSON.parse(data);

          var initial_index = Object.keys(data.sites)[0];

          // ...

One you've parsed it, you'll have an object tree you can traverse.

你已经解析了它,你将拥有一个可以遍历的对象树。