Search code examples
angulartypescriptangular-pipeangular11

Angular Pipe: Convert string into Json and get member value


Is there an Angular pipe which takes a String text, and lets user get an actual value?

String: {"ProductId": "1234", "ProductName": "Computer"}

Expected Pipe:

(item | pipe).productName 
===> results in 'Computer'

(item | pipe).productId
===> results in 1234

Resource:

This following pipe converts an object into json. https://angular.io/api/common/JsonPipe

I need to convert string, and get a member value


Solution

  • I have not seen a pipe like the one you mean but it would probably be something like this if you did it yourself...:

    Created this one and tested it...works pretty great using the description data you provided.

    @Pipe({
      name: 'jsonParse'
    })
    export class JsonParsePipe implements PipeTransform {
    
      transform(value: string, ...args: unknown[]): any {
        return JSON.parse(value);
      }
    
    }
    

    In one of the components I had this defined as a member of the component class:

      data = JSON.stringify({ ProductId: '1234', ProductName: 'Computer' });
    

    and had the HTML like so:

    <div>{{ (data| jsonParse).ProductId }}</div>
    

    Im pretty sure you could spice it up with a bit of overloading to give it more functionality for future use...