Enforced data type for JSON file

After retrieving data from the JSON file, I start by creating a class and defining all the variables obtained in the JSON for strict data typing. For example, my JSON file looks like this:

 {"fname":"Mark","lname":"jhony"}

In Angular, I define the class as follows:

export class user{
 fname: string;
 lname : string;
}

However, I am facing confusion on how to structure the class for the following JSON data:

{"fname":"Mark","lname":"jhony",
 "parcels":[
   {
    "parcelId":123,
    "parcelName":"asd",
    "parcelItems:[
       { 
        "itemId":2,
        "itemName":"perfume"
       },
       { 
         "itemId":4,
         "itemName":"soap"
       }
     ]
]}

I have attempted to include arrays in the class but I am struggling to determine the best approach to handle it in AngularJS.

Answer №1

One common practice is to utilize an interface to define a structure for storing basic values, like in the following example:

interface ProductInfo {
  productId: number;
  productName: string;
}
interface Product {
  productID: number;
  productName: string;
  productItems: ProductInfo[];
}
interface Customer {
  firstName: string;
  lastName: string;
  Products: Product[];
}

When retrieving and parsing JSON data, you can specify the interface to use based on your needs. A simple way to achieve this would be:

const customer = JSON.parse(customerJson) as Customer;

If you prefer to work with a class to include additional methods for handling data, you will need to create an instance of the class using a constructor. This process may look like:

const customerValues = JSON.parse(customerJson);
const customer = new Customer(customerValues);

Answer №2

Yes, this solution appears to be effective.

export interface BaggageItemType {    
    itemNumber: number;
    itemName: string;
}

export interface BaggageType {
    baggageId: number;
    baggageName: string;
    baggageItems: BaggageItemType[];
}

export interface UserType {
   firstName: string;
   lastName: string;
   baggages: BaggageType[];
}

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

Error occurred during the Uglify process: Unable to access the 'kind' property as it is undefined

I developed a project using TypeScript (version 3.9.3) and Node (version 10.16.3), but now I want to minify the code by converting it to JavaScript and running UglifyJS. However, after going through this process, the services that were functioning properly ...

Using a dynamic template URL in a directive

I am currently working with this directive: Directives.js module.directive('vdGuarantees', function () { return { restrict: 'A', template: '<div ng-include="contentUrl"></div>', link: ...

Display a table in the Bot emulator with fields populated by values of class objects

Is there a way to display a table in Bot Emulator with values from a class object? I'm currently struggling to achieve this, as I attempted to use an Adaptive card but encountered difficulties in printing variable values of class objects. It seems I&a ...

Error in AngularJS when attempting to use an expression as a parameter for a function, resulting in a syntax parse

Encountering an issue while attempting to parse this code snippet. I need to pass an expression as a parameter in the ng-click function, but it's not allowing me to do so. If I don't use an expression, then clicking on the album image will clear ...

Using npm to install angular-jsdoc

With angular-jsdoc, I currently generate my documentation using the following command: node .\node_modules\jsdoc\jsdoc.js app -c .\node_modules\angular-jsdoc\common\conf.json -d docs -t .\node_modules\angular ...

Options for caching in Angular

As a newcomer to Angular, I am looking to implement caching. After some searching on Google, I came across a few options like this one: Another option I found is Can anyone recommend the best cache for Angular? My application is a ticketing system where ...

Include JSON elements in the ajaxSubmit function

Here is a snippet of code I am working with: var o_titular = {id:'01',fecha:'2014-01-01'}; var o_dependientes = [ {id:'02',fecha:'2014-02-02'}, {id:'03',fecha:'2014-03-03'} ]; var o_fecha = &apo ...

React-Router's Seamless Deep Sub-Route Redirect Functionality

Lately, I've been in the process of migrating a project from AngularJS + UI-Router + UI-Router-Extras to React + React-Router. A standout feature in UI-Router-Extras that caught my eye and I'd like to incorporate into React-Router is called De ...

Enhancing server-generated content with AngularJS

Is there a way to seamlessly integrate ng-repeat with static content? In other words, is it possible to send static divs and then bind them to a JavaScript array (or create an array from the content and bind it later)? I understand that one solution could ...

Show just a single error message if there are two validation errors present

In my AngularJS timepicker, users can choose multiple time segments for each day. The code has validation to detect duplicates and overlapping time segments. For example, entering 11:00am - 12:00am twice will trigger two error messages: 'Overlapping t ...

Troubleshooting the problem of page refreshing in an Angular JS application

I've been working on an angular application and have implemented "$locationProvider.html5Mode(true)" in my route configuration to eliminate the use of /#/ in URLs. Additionally, I've included base href="/" in index.html and everything functions p ...

Ensure the security of a generic type's value by enforcing type safety

Is there a way to utilize generics to ensure that the type of a value is specific? // Sample array const testArr = [ { id: 3, name: 'Spaghetto', // Type 'string' here shouldNotWork: 3.14, // Type 'number' here ...

Trouble seeing span in ion-item in Ionic 2: How can I display plain text instead?

It seems like I may be overlooking something, as I am experiencing an issue with adding a span to an Ion Item, where the span is not being rendered, nor is the div. <ion-card> <ion-card-title> </ion-card-title> <div> < ...

What is the process for utilizing AngularJS's multiple $http calls to retrieve data from a single PHP file?

I'm currently experimenting with multiple AngularJS ajax calls to a single php file in order to retrieve different json data based on the request. Below is the code snippet I am working with: var myApp = angular.module('myApp', []); myApp ...

I am looking to convert the input format of a timepicker using moment.js to display as 12:38:07 instead of 2018-01-23T12:38:07.439Z

In my project, I am utilizing AngularJS Material for the template and AngularJS for JavaScript. Due to the absence of a timepicker in Angular Material JS, I have opted to use a timepicker provided by Moment.js. The backend of my application is built using ...

"The use of an angular variable to create dynamic HTML content

Looking to build a blog page using AngularJS and running into an issue with the message section. Currently, I have a div set up like this: <div class="post-content"> {{jsonPost.message}} </div> Within the jsonPost.message variable, I have ...

Use Staxon to transform JSON into XML format using Java

I am currently working on converting Json to XML utilizing the following code: public static String jsonToXML1(String source) { String xmlString = null; try { StringWriter stringWriter = new StringWriter(); InputStream inputStream ...

Display a recurring list within an Ionic Pop Up

I am facing an issue with a collection repeat list that includes a search bar at the top of the list. When displayed on a real Android 4.4 device, only 9 records are showing up. I have created a codepen example here, where all the records are displayed co ...

Locating the JSON path within an object

Need help with checking if a specific path is present in a JSON object? var data = { "schemaOne": { "name": "abc", "Path": "i.abc", "count": 5347, "subFolders": [ ] }, "schemaTwo": { "name": "cde", "Path": "i.cde", " ...

Creating a web layout or template using HTML

Currently in the process of developing a website, my goal is to construct html templates that include placeholders for injecting pages/content, menus, and other elements. While I admire AngularJS for its flexibility in achieving this, I fear it may be too ...