Guide to retrieving specific information from a JSON file in an Angular application

Struggling with handling this JSON file

[
    [
        {
            "category": "Bags",
            "productData": [
                {
                    "id": 1000,
                    "name": "Trolley backpack",
                    "short description": "short description",
                    "long description": "LONG DESCRIPTION",
                    "image": "../../assets/images/catalogue/bags/trolleyBackpack.png"
                }
            ]
        },
        {
            "productData": [
                {
                    "id": 1001,
                    "name": "Laptop bag",
                    "short description": "short description",
                    "long description": "LONG DESCRIPTION",
                    "image": "../../assets/images/catalogue/bags/laptopBag.png"
                }
            ]
        } 
    ],
    [
        {
            "category": "Eco",
            "productData": [
                {
                    "id": 1100,
                    "name": "Bamboo Pen drive",
                    "description": "A sustainable choice",
                    "image": "../../assets/images/catalogue/eco/bamboo-pendrive.png"
                }
            ]
        },
        {
            "productData": [
                {
                    "id": 1101,
                    "name": "Bamboo tabletop items",
                    "description": "Eco-friendly products",
                    "image": "../../assets/images/catalogue/bags/bamboo-tabletop.png"
                }
            ]
        }
    ]
]

Implemented a service using http.get. Subscribed to data in app.component.ts:

 Productinfo: any = []

constructor(private service: DataStorageService) {}

ngOnInit() {
  
    this.service.GetProductDetails().subscribe(data => {
      this.Productinfo = data;
    })

}

Encountering challenges accessing the data in app.component.html

<div class="container">
    <div class="row row-cols-sm-4 g-5">
       <div class="col-sm-6 col-md-4 d-flex justify-content-center col-lg-3" *ngFor="let product of Productinfo.productData">
          <div class="card card-cover h-100 overflow-hidden text-white bg-white rounded-5 shadow-lg">
              <img src="{{product.image}}" style="object-fit: cover;">
              <div class="d-flex flex-column ps-3 pe-5 fontName text-light text-shadow-1 h-100"
              style="position: absolute;">
                  <h2 class="pt-5 mt-5 mb-4 display-6 lh-1 fw-bold"
                  style="position: relative;">
                      {{product.name}}
                  </h2>
                  <img
                  src="../../../assets/images/bonjour-logo.png"
                  alt="Logo"
                  width="32"
                  height="32"
                  class="rounded-circle border border-dark bg-dark"
                  style="position: absolute; bottom: 15px;"
                  />
              </div>
          </div>
       </div>
    </div>
</div>

Error observed with Productinfo.productData. Is it necessary to access the productData array in TS file?

Requirement to conditionally display data based on category. Considering usage of *ngIf, seeking better alternatives. Any suggestions?

Appreciate your insights :)

Answer №1

Your data is structured as a nested array of objects, with each object containing fields for "category" and "productData". To properly parse this JSON, you'll need to first iterate over the main array of objects, then loop through the productData array within each object. Utilizing interfaces may be necessary to effectively handle this data structure.

[ <- Begin by iterating over the outer array
        [ <- Then proceed to loop through this array to access the inner object
            {
                "category": "Bags",
                "productData": [ <- Within each object, iterate through this array to access individual productData objects
                    {
                        "id": 1000,
                        "name": "Trolley backpack",
                        "short description": "short description",
                        "long description": "LONG DESCRIPTION",
                        "image": "image.png"
                    }
                ]
            }
        ]
    ]

Answer №2

Rectify the JSON structure:

 [{
  "category":"Bags",
  "productData":[
     {
        "id":1000,
        "name":"Trolley backpack",
        "short description":"short description",
        "long description":"LONG DESCRIPTION",
        "image":"../../assets/images/catalogue/bags/trolleyBackpack.png"
     },
     {
        "id":1001,
        "name":"Laptop bag",
        "short description":"short description",
        "long description":"LONG DESCRIPTION",
        "image":"../../assets/images/catalogue/bags/laptopBag.png"
     }
  ]},{
  "category":"Eco",
  "productData":[
     {
        "id":1100,
        "name":"Bamboo Pen drive",
        "short description":"short description",
        "long description":"LONG DESCRIPTION",
        "image":"../../assets/images/catalogue/eco/bamboo-pendrive.png"
     },
     {
        "id":1101,
        "name":"Bamboo tabletop items",
        "short description":"short description",
        "long description":"LONG DESCRIPTION",
        "image":"../../assets/images/catalogue/bags/bamboo-tabletop.png"
     }
  ]}]

I believe this structure aligns with your expectations.

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

Save Scope in JSON format

Currently, I am developing a web application that dynamically displays specific prompts based on the field in focus. There are several different texts stored as scripts that I want to showcase at these different points. My goal is to incorporate scope dat ...

Converting a Date in PHP and Encoding it in JSON Format

I have a MySQL query that looks like this: <?php $sql = "SELECT * FROM my_table"; $result = mysql_db_query($DBname,$sql,$link) or die(mysql_error()); $rows = array(); while($r = mysql_fetch_assoc($result)) { $rows[] = $r; } print json_encode($row ...

Having trouble locating the export in the TypeScript module

Having a situation where there is a file with an exported object: let btypes:{[key:string]:any} = { "key1":val, //... } export {btypes} I even attempted to use export default btypes Upon importing it using: import {btypes} from "../types& ...

Having difficulty parsing, filtering, or extracting a json.dumps object within a loop

I am looking to extract the first element starting after [{ using the code provided below. [ { "Bkav": { "category": "harmless", "result": "clean", "method": "blacklis ...

Leverage JSON data in JavaScript

Having some trouble figuring out how to incorporate JSON values into my JS script. Any assistance would be greatly appreciated as I am still new to this! Below is the snippet of code where I need the values (lat and lon) to be inserted: var map; functio ...

Saving individual pieces of data in the database

When it comes to storing single data values in a database, what is the most effective method? I have a few ideas. One option is to store all fields in a single_data_table with columns for id, key, and value. Another approach is to save it as a json object ...

Encountered an issue during the Jest test where the error message states 'Cannot call Class constructor Stack without using the keyword 'new''

I have encountered an issue with my Jest test for an AWS CDK configuration import { expect as expectCDK, matchTemplate, MatchStyle } from '@aws-cdk/assert'; import * as cdk from '@aws-cdk/core'; import { KmsMultiregionPrincipalKey } fro ...

Is it possible for changes made to an object in a child component to be reflected in the parent component

When passing an object to the child component using , how can we ensure that changes made to a specific property in the object within the child component are visible in the parent component? In my understanding, changes would not be reflected if we were p ...

Assign a value to a variable within the $_POST array for validation purposes using Codeigniter

I am currently developing a WebSocket based application using Codeigniter. The data is being received as a JSON string (not via a POST Method) and I want to utilize Codeigniter's built-in form_validation method to validate this JSON data. Here are th ...

Utilizing JSON information to pinpoint locations on Google Maps

I've been attempting to place markers on a map based on coordinates stored in JSON format, but it seems I may be missing something in my approach. public class Stadiums { public int ID { get; set; } public string Team { get; set; } ...

Utilizing numerical values in useParams - A beginner's guide

Trying to access specific data from my json file using an ID, like "http://localhost:3001/pokemons/3", leads to a 404 error. All the data is visible at http://localhost:3001/pokemons. It seems that useParams doesn't want me to use id as a number - q ...

JSON multi_select feature in CodeIgniter

I have a dialog form where users can register for championships by selecting from a multi-select dropdown. Here is the code snippet I am using (specifically in Codeigniter): <?php foreach ($championships as $championship) { $options[$championship-&g ...

Retrieve JSON information from a URL via AJAX if applicable

Is there a way to retrieve the JSON data from the following URL and incorporate it into my webpage in some capacity? (Disclaimer: I do not own this website, I am simply utilizing the data for a basic free app.) Although entering the URL directly into the ...

Is it possible to begin the vue root instance by using a .vue class component?

Utilizing vue-class-component allows me to incorporate class syntax and TypeScript type checking within my .vue files. I can easily create .vue files and register them as components using this method, with the exception of the root Vue() instance. This ap ...

Transfer the current Angular project to operate as a separate entity

After successfully migrating my Angular project from version 13 to version 16 step by step, I am now aiming to make it fully standalone before proceeding with the migration to version 17. I am wondering if there is a utility available that can assist me i ...

The 'HTMLDivElement' type does not include the property 'prepend' in Typescript

When working with a typescript method, the following code snippet is used: some_existing_div.prepend(some_new_div) This may result in an error message: [ts] Property 'prepend' does not exist on type 'HTMLDivElement'. However, despi ...

Creating dictionary data in JSON format using Python is a simple process

As a newcomer to Python, I am currently grappling with understanding how to work with dictionaries operations. Here is the data that I have: [{'mesure':'10', 'name': 'mumbai', 'age': '15', &apos ...

A step-by-step guide on how to access the version number in an Angular (v4+) application from the package

Currently, I am attempting to retrieve the version number of my Angular application from package.json where it is stored. Most resources recommend using require to load the JSON file like so: var pckg = require('../../package.json'); console.log ...

Converting JSON into HTML format

Seeking guidance as a developer tasked with rendering JSON to HTML on a webpage. I've taken over for someone else and, despite feeling somewhat in over my head, have managed to build the basic structure using Catalyst/Template Toolkit and Dojo. Now th ...

Converting XML to JSON using Camel

I am facing some challenges while trying to convert an XML file format to a JSON file format in my program. I attempted to use the marshal command, but encountered errors: Exception in thread "main" org.apache.camel.FailedToCreateRouteException: ...