组合多个对象以在Node中创建JSON对象

时间:2018-06-02 21:02:35

标签: javascript node.js express

我正在尝试从多个在线图像/摄影源构建我自己的JSON对象。以下代码应该解释我想要完成的任务:

var searchUnsplash = require('./apis/unsplash');
var searchFlickr = require('./apis/flickr');

function combineObjs(callback) {

    var obj = {} 
    var key = 'item';
    obj[key] = []; 

    searchFlickr.searchFlickr(searchTerm, searchCount, searchPage,
        function (callback) { // each API call is in a separate file with these functions exported 

            obj[key].push(flickrObj); // this does not work 
            // console.log(flickrObj) // this works 
        });
    searchUnsplash.searchUnsplash(searchTerm, searchCount, searchPage, 
        function (callback) {

            obj[key].push(unsplashObj);
            // console.log(unsplashObj)
        });

    console.log(obj)
}

combineObjs();

目标是最终获得如下的JSON对象:

["item": {
    "id": 1,
    "title": 2,
    "content": 3,
    "source": "flickr"
}, 
"item": {
    "id": 1,
    "title": 2,
    "content": 3,
    "source": "unsplash"
}]

等,我可以用来为我的前端供电。

我是javascript的初学者,我正在研究我在教程和文章中学到的东西,所以我可能完全使用错误的方法来实现我的目标。很高兴接受任何指示

搜索功能:

function searchUnsplash(term, count, page, callback) {
    request(`https://api.unsplash.com/search/photos/?per_page=${count}&page=${page}&query="${term}"&client_id=KEY&`, 

    function searchResult(error, response, body) {
        if (!error && response.statusCode == 200) {
        var info = JSON.parse(body)

        for ( var i = 0; i < info.results.length; i++) {

            obj = {
                id: `us-${info.results[i].id}`, 

            }
            callback(obj);

        }

    }

    })
}

module.exports.searchUnsplash = searchUnsplash;

2 个答案:

答案 0 :(得分:0)

这是过分但它会起作用。它可以一次又一次地使用。 :d

运行代码段以查看结果

&#13;
&#13;
class JSONBuilder
{
  constructor(contents=null)
  {
    if(!contents)
    {
      //Private objecy hash that isn't publicly accessible
      var objectHash = {};
      
      //Get stashed item
      this.GetItem = function(key)
      {
        if(!key) throw new Error("Null or Underfined Key Passed.");

        let value = objectHash[key];
        if(!value) throw new Error(`Key : ${key} Not Found in JSON objectHash`);
        return value;
      }
      
      //Set an item in the objecy hash
      this.SetItem = function(key, value)
      {
        if(!key) throw new Error("Null or Underfined Key Passed.");
        if(!value) throw new Error("Null or Underfined Key Not Found.");

        objectHash[key] = value;
      }
      
      //Remove item from the hash
      this.DeleteItem = function(key)
      {
        if(!key) throw new Error("Null or Underfined Key Passed.");
        if(!objectHash[key]) throw new Error(`Key : ${key} Not Found in JSON objectHash`);

        objectHash.DeleteItem(key);
      }
      
      //Turn items into a JSON object
      this.Build = function()
      {
        return JSON.stringify(objectHash);
      }
    }
    else
    {
      //If a string is passed as a paremeter, reconstruct from that
      try
      {
        objectHash = JSON.parse(contents);
      }
      catch(Err)
      {
        console.log("Parsing of JSON Content Failed.");
        throw Err;
      }
    }
  }
}

class Item
{
  constructor(id, source, content, title)
  {
    this.Id = id;
    this.Source = source;
    this.Content = content;
    this.Title = title;
  }
}
let builder = new JSONBuilder();
let itemContainer = [];
itemContainer.push(new Item(1, 'flicker', 'stuff', 'item1'));
itemContainer.push(new Item(2, 'flicker', 'morestuff', 'item2'));

builder.SetItem('items', itemContainer);
console.log(builder.Build());
&#13;
&#13;
&#13;

答案 1 :(得分:0)

首先,您的预期结果不正确。您不能将"item"命名为各个数组条目。一个经过纠正和运作的例子就是这个。

[ {
    "id": 1,
    "title": 2,
    "content": 3,
    "source": "flickr"
}, 
{
    "id": 1,
    "title": 2,
    "content": 3,
    "source": "unsplash"
}]

其次,您将JSON误认为是您的数据结构。 JSON只是文本符号。所以,让我们先看看如何构建合适的数据数组。

let results = [];
results.push( { id:1, title:2, content:3, source:"flickr" });
results.push( { id:2, title:4, content:6, source:"unsplash" });

然后JSON.stringify(results)会将您的results编码为JSON。

最后,将代码中的异步调用与同步调用混合在一起。您需要将结果保存在各个函数的回调中,即您真正异步获取响应时。此外,您需要计算待处理结果并在完成所有操作后调用最终回调。

所以,把所有部分放在一起,在一个假设的假例子中,我们只调用两次搜索函数,所以当两个结果合并时我们回调。

function combineObjs(callback) {  
   let results = [];   
   function partialResult(obj) { 
     results.push(obj); 
     if (results.length=2) callback(results);
   }; 
   searchFlickr(searchTerm, searchCount, searchPage, partialResult);
   searchUnsplash(searchTerm, searchCount, searchPage,partialResult);    
}

combineObjs( function(results) { console.log(JSON.stringify(results)) });