Transforming a JSON string into an object within a variable amount of nested JSON structures

I'm encountering an issue with modifying JSON strings within JSON objects for varying numbers of objects. Allow me to elaborate further with my code and explanations.

I have a factory that supplies JSON objects

//Factory for products
app.factory('productsFactory', ['$http', '$location', function($http, $location){
    var factory = {};
    factory.getlatestProductsList = function(n){
        return $http.get($location.protocol() + '://' + $location.host() + '/server/api/products/latest/'+n);
    }
    return factory;
}]);

This factory returns an uncertain number of objects

0: Object
active: "1"
alias: "baumbach-circle"
date_c: "2016-01-06 08:09:54"
date_u: null
description: "Corrupti fugit iste quo sunt quidem voluptatibus dolorem. Eos velit architecto veritatis doloribus. Corporis sequi cupiditate possimus voluptates ut consequatur. Accusantium libero qui est sunt et."
id_category: "46"
id_product: "25"
id_user: "177"
images: "[{"thumbImage":"http:\/\/lorempixel.com\/250\/150\/?63763","image":"http:\/\/lorempixel.com\/1024\/768\/?52630","position":0},{"thumbImage":"http:\/\/lorempixel.com\/250\/150\/?99795","image":"http:\/\/lorempixel.com\/1024\/768\/?84669","position":1},{"thumbImage":"http:\/\/lorempixel.com\/250\/150\/?17506","image":"http:\/\/lorempixel.com\/1024\/768\/?88926","position":2},{"thumbImage":"http:\/\/lorempixel.com\/250\/150\/?73869","image":"http:\/\/lorempixel.com\/1024\/768\/?91917","position":3},{"thumbImage":"http:\/\/lorempixel.com\/250\/150\/?70019","image":"http:\/\/lorempixel.com\/1024\/768\/?18509","position":4}]"
name: "Baumbach Circle"
__proto__: Object
1: Object
active: "1"
alias: "elta-road"
date_c: "2016-01-06 08:09:53"
date_u: null
description: "Culpa perferendis dolores rerum deleniti vero cumque. Similique explicabo beatae est quo sit nisi. Et a voluptatem nihil in. Voluptates modi qui est ducimus corrupti."
id_category: "46"
id_product: "24"
id_user: "73"
images: "[{"thumbImage":"http:\/\/lorempixel.com\/250\/150\/?53746","image":"http:\/\/lorempixel.com\/1024\/768\/?49502","position":0},{"thumbImage":"http:\/\/lorempixel.com\/250\/150\/?75052","image":"http:\/\/lorempixel.com\/1024\/768\/?77727","position":1},{"thumbImage":"http:\/\/lorempixel.com\/250\/150\/?32463","image":"http:\/\/lorempixel.com\/1024\/768\/?76121","position":2},{"thumbImage":"http:\/\/lorempixel.com\/250\/150\/?61377","image":"http:\/\/lorempixel.com\/1024\/768\/?89434","position":3},{"thumbImage":"http:\/\/lorempixel.com\/250\/150\/?86873","image":"http:\/\/lorempixel.com\/1024\/768\/?82513","position":4}]"
name: "Elta Road"
__proto__: Object

The issue arises from the images JSON being formatted as a string, requiring me to utilize JSON.parse (at least I believe so, given my limited experience) to convert them into JSON

My inquiry is: Is there a simple and elegant method to parse all image data into JSON or must I resort to using forEach? If so, how would the code implementation look like? I aim to achieve this functionality within the factory to avoid redundancy in each controller calling upon it.

If you require any additional information, please do not hesitate to ask and I will gladly provide it. Thank you in advance.

Answer №1

You have the ability to modify the response received from the $http service before sending it back.

app.factory('productsFactory', ['$http', '$location', function($http, $location){
    var factory = {};
    factory.getlatestProductsList = function(n){
        var url = $location.protocol() + '://' + $location.host() + '/server/api/products/latest/'+n;
        return $http({
            method: 'GET',
            url: url
        }).then(function successCallback(response) {
            // You can customize the response here by parsing or editing it
            return response ;
        }, function errorCallback(response) {

        });
    }
    return factory;
}]); 

Answer №2

If you utilize the fact that $http gives back a promise, you can perform some data processing before returning the promise. Please inform me if this approach suits your needs, or if you require assistance in ES5.

factory.getlatestProductsList = function(n){
    return $http.get($location.protocol() + '://' + $location.host() + '/server/api/products/latest/'+n)
    .then(data => data.map(elem => {
       var tmp = Json.parse(elem.images);
       elem.images = tmp
       return elem;
    }));

In ES5:

factory.getlatestProductsList = function(n){
    return $http.get($location.protocol() + '://' + $location.host() + '/server/api/products/latest/'+n)
    .then(function(data) {
       return data.map(function(elem) {
         var tmp = Json.parse(elem.images);
         elem.images = tmp
         return elem;
       });
    });

Answer №3

Here is a code snippet for creating a factory in AngularJS:

//Factory for products
app.factory('productsFactory', ['$http', '$location', function($http, $location){
    var factory = {};
    factory.getlatestProductsList = function(n){
        var url = $location.protocol() + '://' + $location.host() + '/server/api/products/latest/'+n;
        return $http({
            method: 'GET',
            url: url
        }).then(function successCallback(response) {
            var pros = response.data;
            pros.forEach(function(item){
                var pictures = JSON.parse(item.images);
                delete item.images;
                item.images = pictures;
            })
            return pros;
        },function errorCallback(response) {
            console.log('error fetching latest products: ' + response);
        });
    }
    return factory;
}]);

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

What is the process for decoding HTML content that is wrapped within JSON data?

I have a web application built using asp.net that utilizes ajax calls. Below is the code snippet for my web method which successfully responds to the ajax call. ADController adc = new ADController(); DataTable dt = adc.GetGeneral(Convert.ToInt32(A ...

Using dynamic JavaScript appending with the location.href attribute and the ajax-cross-domain.com script for seamless integration

Once I assign this code to load the function on window.onload event: window.onload = initfunction; I am looking to add an AJAX cross domain script to the header: function initfunction() { var dh = document.getElementsByTagName('head')[0]; va ...

Creating a Copy of an Object in JavaScript that Automatically Updates When the Original is Changed

I am in the process of developing a planner/calendar website with a repeat feature. var chain = _.chain(state.items).filter({'id': 1}).head().value(); console.log(chain); After filtering one object, I am wondering how to create a duplicate of c ...

Exploring JavaScript Unit Testing: Essential dependencies for testing with Karma, jasmine, and bootstrap

After creating an application using AngularJS and additional tools based on bootstrap, I am now facing the challenge of testing everything. However, there seems to be a problem with Karma and Jasmine as an exception is thrown when running the tests. The i ...

Facing a cross-domain problem that is blocking my ajax request to fetch data from my express endpoint

Looking to retrieve and showcase data from my node/exprss file (app.js) on my index.html. Utilizing an ajax request to localhost:3000/turtles in frontend.js, but running into cross domain obstacles. APP.JS FILE var express = require('express'); ...

Creating your own JsonConverter in JSON.NET: A step-by-step guide

I have been exploring how to expand upon the JSON.net example provided in In my scenario, I have a subclass that inherits from a base class or interface. public class Person { public string FirstName { get; set; } public string LastName { get; se ...

Guide on loading a JSON file in Play framework utilizing Scala

In my project, I am looking to retrieve a list of cities from a JSON file within one of my controllers. The intention is to then pass this information to a view for display. The location where I have stored the file is: app/assets/jsons/countriesToCities. ...

In my coding project using Angular and Typescript, I am currently faced with the task of searching for a particular value within

I am facing an issue where I need to locate a value within an array of arrays, but the .find method is returning undefined. import { Component, OnInit } from '@angular/core'; import * as XLSX from 'xlsx'; import { ExcelSheetsService } f ...

Update and republish an outdated npm package

After successfully publishing an npm package, I attempted to make an update which unfortunately resulted in some issues. It seems that I made a mistake during the build process. Since it had been a year since my last update, I have forgotten the exact step ...

Determine the frequency of matching elements between an array and a JSON column by comparing the two and counting the number of similar terms

My goal is to develop a basic search engine that can determine the count of properties matching a user input. The data will be stored in JSON format with an array structure, allowing users to perform searches based on their preferences. The comparison pr ...

Notification system for managing recurring tasks

Situation I am currently working on an application where users are assigned daily tasks such as "wash the window, clean the floor," and so on. Each task has a specific recurrence interval and must be completed at least once within that time frame. For e ...

Error message: Attempting to access the property '_layerAdd' of an undefined object in the context of vue and leaflet integration

Encountering an issue while attempting to include a feature group on my map: TypeError: Cannot read property '_layerAdd' of undefined The section of code causing the error: <l-map id="mapid" :zoom="zoom" :center="center" /> var ...

Python does not recognize the Json-like response

After receiving a response using urllib3 (also tested with requests), I decoded it and then used json.loads on it. The data, post-decoding with decode('utf-8'), that I would like to convert into JSON is as follows: json_thing = b'{\n& ...

As I attempted to set up sb-admin-bs4-angular2-master, an application built with Node.js, I encountered an error message while running the npm install command

view image details here After running npm install -g ts-node, I proceeded with npm install only to encounter an error that left me clueless. Subsequently, when attempting npm start, a series of errors related to the gulp server or similar issues emerged. ...

Utilizing a static method from a Class imported from a Node.js module

One puzzling question arises: How can we reference other static methods from within a static method of a class exported from a NodeJS module? Let's consider the following scenario. We have two modules: test1.js var Parent = class { static smetho ...

Is it necessary to specify the JavaScript version for Firefox? (UPDATE: How can I enable `let` in FF version 44 and below)

Our recent deployment of JavaScript includes the use of the let statement. This feature is not supported in Firefox browsers prior to version 44, unless JavaScript1.7 or JavaScript1.8 is explicitly declared. I am concerned about the potential risks of usi ...

Querying the database to check for the presence of a file in a .js file on Google App Engine

I'm currently working on implementing an upload button for users to upload files to our storage system using Google App Engine with Python, as well as HTML and JavaScript for the views. To achieve this, we have an HTML file and a.js script that promp ...

Is there a way to stop TD from going to the next line?

I am using Javascript to dynamically generate a table and I want it to extend beyond the boundaries of the page. When I manually create the table, it works fine and extends off the page, but once I put it into a loop, the <td> elements wrap onto a se ...

The Javascript navigation bar is not displaying properly on mobile devices as it should

After customizing the responsive navbar tutorial from W3Schools using CSS and JS, I encountered an issue. I wanted to include a logo and a web page title before the navbar, which worked perfectly when the webpage was maximized. However, when I resized the ...

Tips on efficiently writing parsed JSON data within an AsyncTask

I am currently developing an application that extracts data from a URL by adding a username and password parameter, parses the data successfully but encounters difficulty in updating or posting it back to the server. private class xyz extends AsyncTask& ...