NetOperator Wibby
NetOperator Wibby

Reputation: 1404

Combine JSON files?

All the questions I've found relating to this have been about combining JSON objects and/or strings. I am using a jQuery plugin called "Fuse", for searching the contents of the files (repo here: https://github.com/krisk/Fuse). This is the code I have so far.

$.getJSON("data/bn1.json", function(data) {
    start(data);
});

$.getJSON("data/bn2.json", function(data2) {
    start(data2);
});

Both JSON files look like this (shortened, for brevity):

[
 {
    "number": "001",
    "name": "Cannon",
    "rarity": "*",
    "damage": "40",
    "element": "Normal",
    "description": "A nice, big Cannon!"
 },
 {
    "number": "002",
    "name": "HiCannon",
    "rarity": "**",
    "damage": "80",
    "element": "Normal",
    "description": "A nice, big Cannon!"
 },
 {
    "number": "003",
    "name": "M-Cannon",
    "rarity": "***",
    "damage": "120",
    "element": "Normal",
    "description": "A nice, big Cannon!"
 }
]

The last JSON file to be called (in this case, bn2.json) is the one that shows up when I search. I want to search in more than two files (it'll be six files in the future). The full JS file for my project is here: https://github.com/IdeasNeverCease/Gingnet/blob/master/scripts/gingnet.js (you can find my JSON files there too).

If anyone can point me in the right direction, I'd greatly appreciate it.

Upvotes: 5

Views: 15413

Answers (2)

NetOperator Wibby
NetOperator Wibby

Reputation: 1404

Thanks to Brad, I came up with a solution:

var allData = [];

$.getJSON("data/bn1.json", function(data) {
    allData = allData.concat(data);
    start(allData);
});

$.getJSON("data/bn2.json", function(data2) {
    allData = allData.concat(data2);
    start(allData);
});

Hooray!

Upvotes: 1

Brad
Brad

Reputation: 163334

Your question boils down to, "how do I merge arrays?" You can use Array.concat().

var allData = [];
$.getJSON("data/bn1.json", function(data) {
    allData = allData.concat(data);
});

$.getJSON("data/bn2.json", function(data2) {
    allData = allData.concat(data);
});

Since you're getting multiple files, it would be best to use promises to wrap these all up and handle them all at once. Untested, but this should get you started:

var urls = [
  'data/bn1.json',
  'data/bn2.json',
  'data/bn3.json'
  // etc.
];

var deferreds = [];
$.each(urls, function (index, url) {
  deferreds.push($.getJSON(url)); // Request all data simultaneously
});

$.when.apply($, deferreds).then(function () { // We have all data, merge it
  var data = [];
  $.each(arguments, function (index, chunk) {
    data = data.concat(chunk);
  });
  start(data); // Do whatever you want to this new collection of data
});

Upvotes: 3

Related Questions