javascript - 将 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 数据以使用键和索引进行访问。请在这方面帮助我。帮助将不胜感激。
谢谢
解决方案
尝试使用以下内容更改您的代码:
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 值或对象
我希望我对你有所帮助。
推荐阅读
- django - 反向 django 自定义管理站点 URL
- asp.net - 从下拉列表中获取 ID?
- ruby-on-rails - Bitbucket 管道 - 是否可以在服务和使用该服务的步骤之间共享文件夹?
- javascript - DataTables - 过滤和比较多列
- google-cloud-platform - 如何安排 AppEngine Flex 实例在 Google Cloud 中停止和启动?
- sharepoint - Sharepoint 列表适配器到 SSIS - 401 NTLM 错误
- react-native - 前台服务访问位置时的权限声明表
- angular - Bytea 使用 Spring Data JPA 和 Angular 在 Postgresql 中持久化和检索
- c# - 为父表检索两个孙数据的 lambda 表达式是什么?
- asp.net-core - Asp.Net Core 中间件中的重定向