Creating a nested JSON file dynamically in Angular: A step-by-step guide

I am looking to dynamically generate a nested JSON file within an Angular project. The data will be extracted from another JSON file, with two nested loops used to read the information. Below is an example of the initial JSON file structure:

{
"data": [
    [
        {"dat": "hello", "date": 4, "Nr": "11", "stat": "bye"},
        {"dat": "hello", "date": 2, "Nr": "13", "stat": "bye"},
        {"dat": "hello", "date": 4, "Nr": "11", "stat": "bye"},
        {"dat": "hello", "date": 2, "Nr": "13", "stat": "bye"},
    ],
    [
        {"dat": "hello", "date": 4, "Nr": "11", "stat": "bye"},
        {"dat": "hello", "date": 2, "Nr": "13", "stat": "bye"},
        {"dat": "hello", "date": 4, "Nr": "11", "stat": "bye"},
        {"dat": "hello", "date": 2, "Nr": "13", "stat": "bye"},
    ]

My goal now is to extract this data and store it in a JavaScript array or map within the TypeScript file.

Answer №1

When dealing with JSON data, you can easily convert a serialized JSON string into an object that can be used in JavaScript or TypeScript by using the JSON.parse method.

Here is a complete example:

const jsonData = `{
    "information": [
        [
            {"name": "John", "age": 30, "id": "001", "status": "active"},
            {"name": "Jane", "age": 25, "id": "002", "status": "inactive"}
        ],
        [
            {"name": "Alice", "age": 40, "id": "003", "status": "active"},
            {"name": "Bob", "age": 35, "id": "004", "status": "inactive"}
        ]
    ]
}`;

const jsonObject = JSON.parse(jsonData);

for (let group of jsonObject.information) {
    for (let person of group) {
        console.log('Person:', person.name, person.id, person.status);
    }
}

Enhance with an Interface

To improve type information and enable auto-completion for the parsed structure, you can add an interface like this:

interface MyJsonData {
    information: { name: string, age: number, id: string, status: string }[][];
}

const parsedObject: MyJsonData = JSON.parse(jsonData);

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

Encountering difficulties when attempting to upload to Google Cloud using a signed URL

Seeking help to troubleshoot why the video upload is not working as expected. I am able to successfully connect to my bucket using a signedURL, but when trying to upload the video, it's not functioning properly. const submitVideo = async () => { ...

Is the vertex count of a Geometry in Three.js increased when it is converted to a BufferGeometry?

Recently, I've been experimenting with the fromGeometry method to convert regular Geometry objects into BufferGeometry objects. To my surprise, I noticed that the number of vertices increases during this conversion process. For instance, consider the ...

What is the best way to eliminate the border of an expansion panel in Material-UI?

Is there a way to eliminate the border surrounding the expansion panel in Material-UI? ...

How to Avoid the "Expression Changed After it has been Checked" Error?

I understand the reason behind the Expression Changed After it has been checked error, however, I am struggling to find a solution to prevent it. Situation Within my Component, there is an ngxDatatable that we manipulate to adjust its width based on cert ...

What causes the difference in behavior between packed and non-packed generics?

When attempting to exclude properties outside of generics, it functions properly but results in a breakdown within the generic context. The issue lies in the fact that Omit<Thing, 'key1' | 'key2'> transforms into Omit<Thing, &a ...

Tips for shuffling the sequence of EJS variables

I am currently working on creating a quiz that consists of multiple choice questions. In order to display the Question, Correct Answer, and 3 other wrong options, I am utilizing EJS variables. The format will be similar to the following example: Question: ...

Typescript polymorphism allows for the ability to create various

Take a look at the following code snippet: class Salutation { message: string; constructor(text: string) { this.message = text; } greet() { return "Bonjour, " + this.message; } } class Greetings extends Salutation { ...

Contrasting @Input with Dependency Injection in Angular 10

Is there a way to pass values from a parent component to a child component without using the @Input decorator? I'm thinking about creating an instance of the Parent class in the constructor (Dependency Injection) and then accessing the variable value ...

Endless loop in XMLHttpRequest()

I am trying to use Ajax in the code snippet below to continuously retrieve a PHP query result until it reaches "6". The code seems to be functioning correctly, but once the result is "6", the script does not stop running. Instead, my CPU fan starts making ...

Arrow indicating the correct direction to expand or collapse all items with a single click

I have successfully implemented the "expand/collapse all" function, but I am facing an issue with the arrow direction. The arrows are not pointing in the correct direction as desired. Since I am unsure how to fix this problem, I have left it empty in my co ...

Insert a new, unique div onto an HTML webpage using JavaScript, ensuring no duplicates are created

Having an issue with this code snippet where nothing is being added. It seems like the variable result may not be taking a number or something else, but I'm not entirely sure why. $(document).ready(function () //document.getElementById(1).style. ...

Is it possible to submit a HTML5 form and have it displayed again on the same page?

Is it possible to simply reload the sidebar of a page containing an HTML5 form upon submission, or is it necessary to load a duplicate page with only the sidebar changed? I am unsure of how to tackle this situation; firstly, if it is achievable in this m ...

Issue: Unable to deserialize Entities.Student object from START_ARRAY token in com.fasterxml.jackson.databind.JsonMappingException

I am facing an issue with my 'JudoClass' object that holds an arrayList of 'Student' objects. Every time I attempt to create a new student, the error mentioned above pops up. Below is the post method code snippet: @POST @Produces(Medi ...

What are some effective methods for locating dual edges within a Half-Edge (DCEL) data structure?

I have implemented a HalfEdge data structure to represent the connectivity between faces in my mesh. While importing an external model, I construct the HalfEdge structure. However, for meshes with numerous triangles, the construction process is time-consu ...

What is the process for importing a JavaScript export file created from the webpack.config file?

Issue at Hand In the process of testing APIs, I encountered a dilemma in setting up either the DEV or Production environment. This involved configuring API endpoints for local testing and preparing them for production use. To achieve this, I utilized NOD ...

Extract the value of an HTML tag and store it in a PHP variable

I have successfully implemented JavaScript code to dynamically update the value of an input tag in my popup. However, when I try to echo out this updated value using a PHP variable within the same popup, it doesn't seem to work as expected. Despite un ...

Delivering objects from controller in AngularJS

I'm currently working on a project where I need to retrieve objects from the controller. Here's a snippet of my code: score.component.js: angular.module('score').component('score',{ templateUrl : 'app/score/score.t ...

Designing Angular 1 table row components with future migration to Angular 2 in consideration

Issue with AngularJS nested directives placement outside parent element Encountering the same challenge in my project using Angular 1.4, but I am also aiming to construct the rows as Angular 2 components which prevents me from using "replace: true". I am ...

What are the ways to activate an element in vue js?

Is there a way to modify the code so that the function triggers with just one click instead of two? export default { methods: { remove(){ $('.remove-me button').click( function() { removeItem(this); }); ...

Can you give me some insights about what an Action Creator is?

function createRefDoneAction(widgetsArray: widget[]): WidgetAction { return { type: actionTypes.REFRESH_WIDGET_DONE, widgets: widgetsArray }; } Could you please clarify the necessity of having two sets of parameters (e.g. 'wid ...