如何仅从URL记录json的id?

时间:2018-05-28 05:08:21

标签: json node.js parsing url

这是我的代码:

var request = require('request');
request('http://www.supremenewyork.com/mobile_stock.json', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.

我只想记录" id" json中的每个对象,我在如何做到这一点。我用在atom中编码的节点运行它。您可以在浏览器中复制粘贴网址以查看完整的json

2 个答案:

答案 0 :(得分:0)

我认为你是初学者,所以我不使用map(),它更容易实现,

将答案视为伪代码

for(let i=0;i<body.products_and_categories.length;i++){
    for(let j=0;j<body.products_and_categories[i].length;j++){
        let id = body.products_and_categories[i][j]
        // whatever you want to do with id do
    }
}

答案 1 :(得分:0)

你可以简单地这样做

const request = require('request')
request('http://www.supremenewyork.com/mobile_stock.json', function(error, response, body) {
  const ids = Object.values(JSON.parse(body).products_and_categories).reduce((o, items) => o.concat(items.map(({
    id
  }) => id)), [])
  console.log(ids)
})