首页 > 解决方案 > 将 JSON 标头和行隐藏到 Node JS 中的对象键

问题描述

我在 Node JS 中以 JSON 格式从 API 获取数据。但是 JSON 具有标题和行格式数据(还附有屏幕截图)。它包含数据“供应商、价格、SKU、错误”。我想把这些数据放在 Object 下面。我可以在循环中使用 Keys 访问其中的任何一个。例如(产品.价格)在此处输入图像描述

enter code here

let new_products = {
  product: {
    Vendor: String,
    Price: String,
    SKU: String,
    error: String
  }
};

I tried the many solutions and get one solution is working but its giving the whole data in one row not in the separate variable.[![enter image description here][2]][2]. The below is the code.

const request = require('request');
const { json } = require('express');
const { Parser } = require('json2csv');

let new_products = {
  product: {
    Vendor: String,
    Price: String,
    SKU: String,
    error: String
  }
};

const options = {
  method: 'GET',
  url: 'https://api.dexi.io/runs/f58f7795-c11a-478c-b670-c7ae5df8677b/latest/result',
  headers: {
    accept: 'application/json',
    json: true,
    'x-dexiio-access': '9d56ee1281967df725exxxxxxxxxxx',
    'x-dexiio-account': '5e597fexxxxxxxxxxxxxxxxxxx'
  }
};

request(options, function (error, response, body) {
  if (error) throw new Error(error);
  var JSONdata = JSON.stringify(body);
  pro = JSON.parse(body);
  product = pro.json;

for(var key in pro) {
  for(var innerKey in pro[key]) {
    console.log("Key: " + innerKey + " value: " + pro[key][innerKey]);
 }      
}
});

我的目的是格式化对象中的 API 数据以使用键和索引进行访问。请在这方面帮助我。帮助将不胜感激。

谢谢

标签: javascriptnode.jsjsonreactjsapi

解决方案


尝试使用以下内容更改您的代码:

request(options, function (error, response, body) {
  if (error) throw Error(error);
  let JSONdata = JSON.parse(body);


  console.log(typeof JSONdata); // JSONdata is an object, so you can start to manipulate it
  console.log(JSONdata); // show in console the object

  for (var key in JSONdata) {
    for (var innerKey in JSONdata[key]) {
      console.log("Key: " + innerKey + " value: " + JSONdata[key][innerKey]);
    }
  }
});

我在 CodeSandbox 中发布了一个示例

来自 MDN 文档: https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

JSON.parse() 方法解析一个 JSON 字符串,构造该字符串所描述的 JavaScript 值或对象

我希望我对你有所帮助。


推荐阅读