developer tip

화면에 [Object Object]가 아닌 JSON 표현을 표시하는 방법

optionbox 2020. 8. 26. 07:47
반응형

화면에 [Object Object]가 아닌 JSON 표현을 표시하는 방법


베타 버전으로 AngularJS 2 응용 프로그램을 만들고 있습니다. 내 페이지에서 객체의 JSON 표현을 표시하고 싶지만 표시 [Object Object]되지 않습니다.{key1:value1 ....}

구성 요소에서 다음을 사용할 수 있습니다.

get example() {return JSON.stringify(this.myObject)};

그런 다음 템플릿에서 :

{{example}}

그러나 객체 배열이 있고 이러한 객체 목록을 인쇄하려면 어떻게 할 수 있습니까?

사용 :

<ul>
   <li *ngFor="#obj of myArray">{{obj}}</li>
</ul>

결과는 다음과 같습니다.

-[오브젝트 오브젝트]
-[오브젝트 오브젝트]
-[오브젝트 오브젝트]
-[오브젝트 오브젝트]

등등. JSON으로 표시하는 방법이 있습니까?


웹앱의 개체 내부에있는 내용을 보려면 구성 요소 HTML 템플릿에서 json 파이프 를 사용하십시오 . 예를 들면 다음과 같습니다.

<li *ngFor="let obj of myArray">{{obj | json}}</li>

Angular 4.3.2를 사용하여 테스트되고 유효합니다.


각도 파이프 json을 사용할 수 있습니다.

{{ jsonObject | json }}

JSON 객체를 반복하려면 : Angluar (6.0.0+)에서 이제 파이프를 제공합니다 keyvalue.

<div *ngFor="let item of object| keyvalue">
  {{ item.key }} - {{ item.value }}
</div>

또한 읽으십시오

JSON 만 표시하려면

{{ object | json }}

객체 콘텐츠를 JSON으로 덤프하는 것은 ngFor. 예:

목적

export class SomeComponent implements OnInit {
    public theObject: any = {
        simpleProp: 1,
        complexProp: {
            InnerProp1: "test1",
            InnerProp2: "test2"
        },
        arrayProp: [1, 2, 3, 4]
    };

마크 업

<div [innerHTML]="theObject | json"></div>

출력 (가독성 향상을 위해 미화기를 통해 실행, 그렇지 않으면 단일 행으로 출력 됨)

{
  "simpleProp": 1,
  "complexProp": {
    "InnerProp1": "test1",
    "InnerProp2": "test2"
  },
  "arrayProp": [
    1,
    2,
    3,
    4
  ]
}

또한 더 큰 JSON 데이터를 더 읽기 쉽게 표시하는 JSON 포맷터 및 뷰어를 발견했습니다 (JSONView Chrome 확장 프로그램과 유사) : https://www.npmjs.com/package/ngx-json-viewer

<ngx-json-viewer [json]="someObject" [expanded]="false"></ngx-json-viewer>

값을 얻을 수있는 두 가지 방법이 있습니다.

  1. 점 표기법 (obj.property)을 사용하여 객체의 속성에 액세스합니다.
  2. 예를 들어 obj [ "property"]와 같은 키 값을 전달하여 객체의 속성에 액세스합니다.

<li *ngFor="let obj of myArray">{{obj | json}}</li>

새 구문으로 다른 사람의 답변 업데이트 :

<li *ngFor="let obj of myArray">{{obj | json}}</li>

if you have array of object and you would like to deserialize them in compoent

get example() { this.arrayOfObject.map(i => JSON.stringify (i) ) };

then in template

<ul>
   <li *ngFor="obj of example">{{obj}}</li>
</ul>

this.http.get<any>('http://192.168.1.15:4000/GetPriority')
  .subscribe(response => 
  {
  this.records=JSON.stringify(response) // impoprtant
  console.log("records"+this.records)
  });

참고URL : https://stackoverflow.com/questions/34864184/how-to-display-a-json-representation-and-not-object-object-on-the-screen

반응형