user15293929
user15293929

Reputation:

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

Upvotes: 2

Views: 5663

Answers (3)

user15293929
user15293929

Reputation:

This will also work:

Typescript:

export class ToJsonPipe implements PipeTransform {
  transform(value: string): any {
    try {
      return JSON.parse(value);
    } catch {
      return null;
    }
  }
}

HTML:

{{ (item?.request | toJson)?.ProductName }}

Upvotes: 0

bloo
bloo

Reputation: 1560

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...

Upvotes: 2

mwilson
mwilson

Reputation: 12960

You can either make a custom pipe like Ashwyn called out or just make a function in your component to do the same

Stackblitz

Component.ts

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular ' + VERSION.major;
  str = '{"ProductId": "1234", "ProductName": "Computer"}';

  parseJson(str: string): any {
    return JSON.parse(str);
  }
}

Template.Html

<div>{{parseJson(str).ProductName}}</div>

I would say if you think you're going to need to use similar functionality throughout your app, make a pipe. If this is a one-time thing, just create a function within the component.

Upvotes: 0

Related Questions