What is the best way to set up a JSON attribute with properly formatted JSON data?

Within this code snippet, the variable some is assigned a JSON string that requires expansion and proper indentation for improved readability.

export class MyComponent implements OnInit {
      some:any = JSON.parse('[{"id":"EN","fill":"blue","classb":"FR someclass"},{"id":"US","fill":"hsl(240, 100%, 35%)","classb":"someclass"},{"id":"ES","fill":"hsl(240, 100%, 60%)","classb":"someclass"},{"id":"IT","fill":"hsl(240, 100%, 90%)","classb":"someclass"}]');

      getStyle(zoneId:string):String{
        var test = this.some.find(x => x.id === zoneId);
        if( test === undefined) return "#000000";
        if( test.fill != undefined) return test.fill;
           return "red";
      }
}

Is there a way to manage properly indented JSON when initializing TypeScript/Angular class members?

Answer №1

If you want to create a JSON string with formatted content, you can utilize template strings with backticks in ES6 JavaScript:

class MyCustomComponent {
  data = JSON.parse(`
    [
      {
        "id": "EN",
        "fill": "blue",
        "classb": "FR someclass"
      },
      {
        "id": "US",
        "fill": "hsl(240, 100%, 35%)",
        "classb": "someclass"
      },
      {
        "id": "ES",
        "fill": "hsl(240, 100%, 60%)",
        "classb": "someclass"
      },
      {
        "id": "IT",
        "fill": "hsl(240, 100%, 90%)",
        "classb": "someclass"
      }
    ]
    `);
}

Answer №2

Utilize an Object for optimal functionality. JSON is a crucial component of JavaScript, making it unnecessary to embed a string within.

Here's an illustration:

export class MyComponent implements OnInit {
  some = [
    {"id": "EN", "fill": "blue", "classb": "FR someclass"},
    {"id": "US", "fill": "hsl(240, 100%, 35%)", "classb": "someclass"},
    {"id": "ES", "fill": "hsl(240, 100%, 60%)", "classb": "someclass"},
    {"id": "IT", "fill": "hsl(240, 100%, 90%)", "classb": "someclass"}
  ];

  getStyle(zoneId: string): string {
    var test = this.some.find(x => x.id === zoneId);
    if (test === undefined) return "#000000";
    if (test.fill != undefined) return test.fill;
    return "red";
  }
}

This method ensures comprehensive tooling and support at the language level while enabling diverse formatting options inherent in JavaScript.

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

Set up Spring Boot to accept solely the necessary JSON information

When retrieving data from an API and receiving a response in the form of an object, I used to create a POJO that matched the object structure and then filled in the data. However, this approach became cumbersome when dealing with APIs that returned hundred ...

JSON structure in a loop

I'm facing an issue with looping through my JSON data. Although I am only looping through "id_first", after printing 1 and 2 correctly, it then moves on to "id_second" and prints undefined. How can I make sure that my loop only prints id first? Here ...

Vue HeadlessUI Error: The function vue.defineComponent is not recognized

Trying to incorporate @headlessui/vue into my nuxt project has been a challenge. My attempt at using it looks like this: <template> <Menu> <MenuItems> <MenuItem>Item</MenuItem> </MenuItems> </Menu&g ...

Implementing atob in Angular's interface

Looking for a solution to a token storage issue, my initial thought is that interfaces might be the way to go. Presently, my login code looks like this: import { Component } from '@angular/core'; import { FormBuilder } from '@angular/forms&a ...

When working with TypeScript in Node, the module ""http"" does not have a default export available

const httpModule = require('http'); httpModule.createServer((req, res) => { res.end('Hello World'); }).listen(3000, () => console.log('Server is running on port 3000')); I've installed @types/node but ...

Swapping the content of the API response with Angular 11 in the HTML

When the output of row.remarks is 1, I want to display it as "passed" and when it's 0, I want it to be displayed as "fail" in the HTML while using mat-table. HTML <ng-container matColumnDef="remarks"> <th class="font& ...

Remove any null or blank values from a JSON field within a MYSQL array

Within a table, there is a JSON field where arrays containing data are stored. For instance: ["a", "", "c"] ["", "", ""] ["a", "b", "c"] The task is to remove empty values from this field and obtain: ["a", "c"] null ["a", "b", "c"] Afterward, update ...

Transforming table data into a JSON format

My goal is to generate a specific JSON format from a table. The table consists of rows and 4 columns. You can view my table here. I aim to create a JSONArray based on the table. The first value in the left column serves as the key in the JSON, while the la ...

HTML experiences confusion as JSON tosses undefined data

Can someone assist me with API integration? I am new to this and trying to display the Poster, Title, and Year from an API URL. Here is the code I have been working on. When I log in, it shows JSON in an array but throws "undefined" in front-end. Your help ...

Organizing an angular expansion panel

I am currently dealing with an expansion panel that has a lot of content. The layout is quite messy and chaotic, as seen here: https://ibb.co/Y3z9gdf It doesn't look very appealing, so I'm wondering if there is a way to organize it better or ma ...

What are the specific purposes of utilizing semantic versioning (semver) notation within the package.json file?

Could someone clarify the specific distinctions between the semver notations found in package.json file? I'd appreciate a detailed explanation. ...

Working with varying data types in JSON using Circe

When dealing with different data types in the same JSON field, such as: "need_exp":1500 or "need_exp":"-" How can this be handled without completely rewriting the decoder? Is there a way to instruct the decoder to automatically convert all integers to ...

"Setting Up a Service in Angular: A Step-by-Step Guide

I am facing an issue with a root service that contains composition within it, as shown below: import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class MapService { private rmap: RMap; ini ...

How to implement a toggle button in an Angular 2 application with TypeScript

Currently, I'm working with angular2 in conjunction with typescript. Does anyone know how to generate a toggle button using on - off?. ...

I find certain operations within certain types to be quite perplexing

I have defined two different types as follows: interface ChangeAction{ type: 'CHANGE' payload: string } interface DeleteAction { type: 'DELETE' payload: number } Now, I want to add a prefix to each value of the type ke ...

Developing a Web service in .NET 4.0 for fetching JSON data on Android devices

Currently, I am without any code at hand. My task involves building a webservice that can retrieve data from a database in JSON format to be used in an Android application. I'm feeling a bit lost on how to get started with this project. Any guidance o ...

Receiving distinct data from server with Ionic 2 promises

Utilizing ionic 2 RC0 with promises to retrieve data from the server, I am facing an issue where I consistently receive the same data in every request due to the nature of promises. Hence, my question is: How can I tackle this problem and ensure differen ...

Why is my Angular2 *ngFor not showing the contents of my array?

Currently delving into Angular 5 and immersing myself in a crash course. I've managed to progress past just using an ngFor directive, but as I tackle part of a practice assignment, I'm encountering an issue where the data won't loop and disp ...

Uploading JSON object to server using Angular

I am currently utilizing json-server along with db.json. In the db.json file, there is an empty array "feedback":[] where users should be able to submit feedback from the application. However, I am facing an issue where nothing is being pushed into the se ...

Utilizing NSURL for constructing new posts on a Rails server via JSON may involve redundant parameters

One problem I'm encountering is that when I make a POST request to a rails server to create a new post using code from the iPhone simulator, the parameters are being sent twice. NSDictionary *thestuff = [NSDictionary dictionaryWithObjectsAndKeys: ...