Combine several JSON files into a single file

After spending countless hours searching on Google, I finally gathered the courage to ask my question here.

I have several json files.

localhost/feed01.json
localhost/feed02.json
localhost/feed03.json

All of the json file structures are similar to this example, but contain random data such as random, id, date type, etc...

[
        {
            "id":1,
            "date": "12/12/2011",
            "type": "Run",
            "distance": "3 miles",
            "comments": "This was really hard",
            "minutes": 36
        },
        {
            "id":2,
            "date": "12/11/2011",
            "type": "Bike",
            "distance": "6 miles",
            "comments": "All down hill...felt like nothing",
            "minutes": 30
        },
        {
            "id":3,
            "date": "12/10/2011",
            "type": "Walk",
            "distance": "2.5 miles",
            "comments": "Shouldn't have taken the dog",
            "minutes": 45
        }
]

Now, I am looking to combine all these JSON files into one and sort them by date by default (upon initialization). What is the most effective method to merge and sort using backbone.js utilizing collections?

Answer №1

Backbone offers the flexibility to customize backbone.sync using options

  • By providing a target URL as an option to collection.fetch, you can override the default URL
  • Setting add: true will add models to the collection without resetting it

This allows you to create a collection like this:

var c = new Backbone.Collection();
c.fetch({
    url: ('localhost/feed01.json'),
    add: true
});
c.fetch({
    url: ('localhost/feed02.json'),
    add: true
});
...

To execute a callback once all fetch operations are complete, you can utilize a jQuery deferred object

var files = ['localhost/feed01.json', 'localhost/feed02.json', 'localhost/feed03.json'];
var c=new Backbone.Collection();
var dfds = [], dfd, i, l;
for (i=0, l=files.length; i<l;i++) {
    dfd = c.fetch({
        url: (files[i]),
        add: true
    });
    dfds.push(dfd);
}

$.when.apply(null, dfds).done(function() {
    console.log(c.pluck('id'));
});

Answer №2

To combine data, simply create a collection and populate it with arrays containing JSON objects or model representations. To make this process possible, you can customize the fetch method by making three separate ajax calls, utilizing jQuery deferreds to ensure all data is gathered and added to the collection before resolving the fetch request.

To modify the sorting logic, you must override the collections' comparator method to sort according to your specific criteria.

For instance, you could specify it like this:

comparator: function(model) {
    return +new Date(model.get('date'));
}

This will sort the data based on the date field.

If you happen to define the comparator after adding models to the collection, remember to call the sort method to ensure that the models are sorted correctly as per the defined rules of the comparator.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporate a fresh label for a function utilizing AngularJS

I want to insert a new HTML tag with an event attached to it. Here is an example of what I am trying to achieve: <html ng-app="module"> <head> <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script&g ...

Malfunction detected in Json autocomplete function

Currently, I am working on implementing an auto-complete search feature using data from my database. The PHP code below creates an array for this purpose: $leaders= mysql_query("SELECT model_name,model_id FROM models ORDER by model_name D ...

Error message: The recursive function is unable to return a value when operating

My current task involves solving this problem recursively: Clean the room function: given an input of [1,2,4,591,392,391,2,5,10,2,1,1,1,20,20], create a function that organizes these into individual arrays that are ordered. For example, answer(ArrayFromAb ...

Implementing click events to control GSAP animations in Next.js

I'm having trouble figuring out how to pause/start an animation using GSAP in Nextjs. Specifically, I can't seem to work with a tl.current outside the useEffect hook within this component. My goal is that when I click on the first .imgWrapper ele ...

How can I send and retrieve multiple variables in a URL using WordPress?

There seems to be an issue where I can only retrieve the first variable, specifically "product_category," from the URL http://localhost/coffeesite/?product_category=coffee&brand=bourbon. When I output JavaScript to confirm that the variables are set, ...

The DELETE request in my app using React Native and Fetch API is experiencing difficulties, although it is successfully working when tested in

We are facing an issue with our API while querying through React Native. Surprisingly, GET and POST requests work perfectly fine in both our app and Postman. However, the DELETE functionality seems to be failing on the app, even though the same request w ...

After restarting, Nuxt 3 runtime configuration values do not get updated with environment variables

Encountered a challenge with updating variables in runtimeConfig that rely on environment variables. When the application is built with values from the .env file like: API_URL=localhost:3000 The console displays localhost:3000. However, upon stopping th ...

Retrieve the HTML representation of a progress bar in Ext JS 3.4 prior to its rendering

Is it possible to obtain the HTML representation of a progress bar before it is rendered anywhere? I am currently using a custom renderer for rendering a progress column in a grid: renderer: function( value, metaData, record, rowIndex, colIndex, store ) ...

Using Fetch API in NextJS requires pressing the Enter key twice for it to work properly

The functionality of this component should display JSON data in the console log after entering input into the search bar and hitting the enter key. However, there is a lag where the data doesn't show until the enter key is pressed a second time. Addit ...

Execute a file upload and deletion process upon receiving a notification from inotifywait

I currently have a script set up to continuously upload files to a server, and once the upload is successful, it returns a JSON object with details about the file. Is there a way I can implement a second script to monitor for this confirmation and delete t ...

Develop a TypeScript class that includes only a single calculated attribute

Is it advisable to create a class solely for one computed property as a key in order to manage the JSON response? I am faced with an issue where I need to create a blog post. There are 3 variations to choose from: A) Blog Post EN B) Blog Post GER C) Bl ...

What is the best way to prevent Firefox from storing the data of a textarea in the local environment?

I have been developing a website locally, and I have noticed that there are numerous <textarea> elements present on the site. One issue I am facing is that whenever I reload the site, the content within the <textarea> remains the same. This pe ...

I'm curious, what is the exact function of ...state?

Just dipping my toes into NgRx (redux) within Angular and I'm a bit puzzled by the use of ...state in the code snippet below. My understanding is that it functions as spread operator, but I can't grasp why the data attributes from the Interface S ...

Problem with a for loop: retrieve only the final item

Using the fileReader to read the content of selected files and appending it to the DOM creates a paragraph element for each file. However, when attempting to store each file's content in local storage, only the last item is being saved. What could be ...

Elements on the page are quivering as a result of the CSS animation

When a user clicks anywhere on a div, I have added a ripple effect to give it some interaction. However, there is an issue where the element shakes and becomes blurry when the page is in full screen mode until the ripple effect disappears. Below is the Ja ...

What is the best way to remove extra information from a redirect URL?

Implementing Discord login OAuth2 in JavaScript has been quite a journey. I have managed to redirect to '/auth' upon completion, but the URL for that page comes with additional information like '/auth#token_type=Bearer&access_token=12eka ...

Ways to tally elements that have been dynamically loaded onto the webpage through AJAX requests

My page has a dynamic region that is continuously updated using jQuery's .ajax and .load methods. In order to submit the form, there need to be at least 3 of these 'regions', so I have to keep track of the number of DIVs with a specific cla ...

Obtaining the id in JavaScript from PHP to display information

This is the code I've written: <textarea id="summernote<?php echo $u->id ?>" name="isi" placeholder="Write here" style="width: 100%; height: 100px !important; font-size: 14px; line-height: 18px; border: ...

Is it possible for ajax to provide me with the information regarding the data size of the URL

Is there a way for the xjr object to access the total data size in KB or MB? I have been using the progress event and it can track this, so I was curious about obtaining the total data size. Here is the code snippet: var container = Pub.el('#super-1 ...

A guide on manipulating JSON data with the JRS223 preprocessor tool in JMeter

The structure of the JSON body is as follows: { "access_key": "", "erid": "", "ch_sms": { "messages": [ { "urlsh": false, ...