What is the correct way to properly parse JSON attributes containing slashes?

I have 2 Custom Interfaces:

DataModel.ts

export interface Entry{
id: number,
content: Note
}

export interface Note{
message: string
}

These interfaces are utilized in typing the HttpClient get request to fetch an array of Entries:

DataService.ts

getEntries():Observable<DataModel.Entry[]>{
  return this.http.get<DataModel.Entry[]>(DataService.API+'entries')
  .pipe(
    retry(3),
    catchError(this.handleError)
  );

The JSON data retrieved looks like this:

[
{
"id":12345,
"content":
"{\"message\":\"Example note\"}"
}
]

However, when attempting to access the 'message' property as defined in the Interface, the slashes interfere with proper conversion from JSON to the specified object structure.

this.dataService.getEntries().subscribe(entry=>{
   console.log(entry[0].content); // {"message":"Example note"}
   console.log(entry[0].content.message) // undefined
});

What is the most efficient approach to address this issue? Existing solutions found online seem complex and cumbersome. Surely Angular offers a more straightforward solution.

Answer №1

Utilizing the map operator from rxjs/operators is crucial before returning data from the service.

By employing map (rxjs), I was able to extract and process the summary.

Take a look at the demo (observe console on button click)

Service

import { Injectable } from '@angular/core';
import { of, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Report } from './types';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class DataService {

  constructor(private http: HttpClient) { }

  getReports(): Observable<Report[]> {

    return this.http.get<any[]>('api')
      .pipe(
        map(
          values =>
            values.map(val => {
              val.summary = JSON.parse(val.summary)
              return val;
             }
            )
        ));
  }

  // mock method for demonstration purposes
  mockGetReports() {
    return of<any[]>([
      {
      "reportId":1777,
      "summary":
      "{\"text\":\"example\"}"
      }
      ])
      .pipe(
        map(
          values =>
            values.map(val => {
              val.summary = JSON.parse(val.summary)
              return val;
             }
            )
        ));
  }

}

Answer №2

Have you considered using JSON.parse()? If that doesn't work, you might want to check out this helpful npm library.

I trust that one of these options will help resolve your problem.

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

Retrieve the highest 10 values from a JSON document using jQuery

I am working with a JSON file in my jQuery project, and I need to display only the top 10 values with the highest numbers. For instance: JSON: { "value": { "number": "12", "number": "11", "number": "10", "number": "9", "number": "8", ...

Connecting two divs with lines in Angular can be achieved by using SVG elements such as

* Tournament Brackets Tree Web Page In the process of developing a responsive tournament brackets tree web page. * Connection Challenge I am facing an issue where I need to connect each bracket, represented by individual divs, with decorative lines linki ...

Error message encountered: Missing property status in TypeScript code

An error occurs in the refetchInterval when accessing data.status, with a message saying "property status does not exist" chatwrapper.tsx const ChatWrapper = ({ fileId }: ChatWrapperProps) => { const { data, isLoading } = trpc.getFileUploadStatus.use ...

Angular Error - TS2322: The specified type of 'Object | null' cannot be assigned to 'NgIterable<any> | null | undefined'

I encountered an error in homes.component.html while trying to run my Angular project to showcase a list of homes from a JSON file. https://i.stack.imgur.com/D0vLQ.jpg Json File [ { "image_url": "https://images.unsplash.com/ph ...

Stop receiving notifications for channel events in Stream with the GetStream.io Chat API

I'm having trouble understanding how to stop listening for channel events in JavaScript using the Stream Chat API. According to the documentation: // remove the handler for all "message.new" events on the channel channel.off("message.new", myChanne ...

When using JsonConvert.DeserializeObject, it may struggle to locate integer members within the JSON object

I'm facing a strange issue where all my classes deserialize properly except for one particular class that contains three int values. When I use the trace writer setting, Json.Net reports that it cannot find the members for this specific class, and I a ...

Troubleshooting radio name input binding in Angular 2

In Angular2, there seems to be an issue with one-way binding to the name attribute for a group of radio inputs. For example: <div [ngFormModel]="form"> <input type="radio" [name]="varName" [id]="id1" ngControl="r1"> <input type="radio" ...

Is it possible to modify the content of an element with a click event in Angular/HTML?

How can I implement a feature in my mat-accordion using mat-expansion-panels where the text becomes underlined when the panels are clicked? I want the title to be underlined when the panels are open and for the underline to disappear when they are closed ...

Upon implementing a custom adapter and incorporating JSON, the application unexpectedly crashed

An error occurred: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 in spinner public void RetrieveData() { JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener ...

How to efficiently use ResponseEntity for user registration via POST method

Currently, I am in the process of constructing a REST API for my website's backend. One Controller that I have set up is for registering new Users: // CREATE A USER @PostMapping("/register") public ResponseEntity<?> createUser( @Request ...

Creating a RESTful API with Express, Firestore, Cloud Functions, and TypeScript

In my quest to create a REST API for my app, I've been delving into tutorials on Firestore & Cloud Functions. Unfortunately, all the ones I've come across are either outdated or simply don't work. This has been quite frustrating for me a ...

Ajax is able to fetch a JSON string, however it struggles to iterate through the successful data as an

My current project involves creating a graph using d3.js. I came across some php code that fits my needs perfectly. However, I am working with c# and Visual Studio, so I need to convert it into asp.net. For starters, I want to input some hardcoded sample d ...

Tips on implementing a script injected through the JS console to update form data in an Angular webpage and ensure that the changes are successfully saved

I am currently working on enhancing an existing electron app integrated with Angular. The main goal is to inject a script once the application is loaded in order to add a hotkey for efficiency. This hotkey should automatically click an edit button, input s ...

Steps to troubleshoot a simple function that manages asynchronous tasks

Looking to develop a versatile function that can handle async functions, execute them, and catch any errors that may arise. Coming from a javascript background, I initially managed to create a function that did just this. However, my attempt to enhance it ...

Issue with React TypeScript: Only the first state update takes effect, despite multiple updates being made

Check out this sandbox I created here. When you leave any of the form inputs blank, I should be seeing 3 errors but instead, I only get one. Can anyone explain why this is happening? import React, { ChangeEvent, useState } from 'react'; import { ...

Options for authentication with Spring Boot and Angular version 2 or 4

As I prepare to integrate user authentication in my app, I realize this is my first time working on an Angular + Spring project. I am interested in learning about the various options available for authentication. While I don't need a step-by-step guid ...

Determine the index of items within an array of objects in Lodash where a boolean property is set to true

I am new to using lodash after transitioning from C# where I occasionally used LINQ. I have discovered that lodash can be utilized for querying in a LINQ-style manner, but I'm struggling to retrieve the indexes of items in an array of objects with a b ...

Is it possible for me to send JSON data using a form to HTTP_RAW_POST_DATA?

Currently, I am in the process of creating a web interface for code that is typically designed to run on Android devices. I transmit JSON data and retrieve the data by using the following method: $json = json_decode($HTTP_RAW_POST_DATA,true); Is there a ...

Tips on obtaining checkbox values other than "true"

Having trouble retrieving the values of selected checkboxes instead of displaying "Custom Category"? I've attempted to access the values and attributes with no success. I'm aiming to display the values of the selected checkbox. app.component.ht ...

JSONPath: Finding data based on dates

Is it possible to use JSON path to filter data by date range if you have JSON data with dates as keys for the objects? For instance, in the given example, how can you retrieve all book titles with publication dates falling between specific x and y dates? ...