2016-10-27 2 views
1

이상한 꽤 형식화 된 방식으로 내 JSON 인쇄하려면 노력하고있어 내 JSON \ 함께 반환하고 꽤 인쇄되지 않는 유지합니다.각도 2 prettify JSON 파이프 필터

나는이 솔루션을 plnkr에서 사용할 수 있지만 실제 응용 프로그램에서는 사용할 수 없습니다. 아래 이미지는 plnkr에있는 것과 비슷한 JSON 인쇄물입니다.

왜 이런 일이 일어나고있는가요?

Plnkr 샘플 : https://plnkr.co/edit/ZqOXS30XPTu9ponWFdgZ?p=preview

코드 파이프 :

@Pipe({ 
    name: 'prettyprint' 
}) 
export class PrettyPrintPipe { 
    transform(val) { 
    if(typeof(val) == "undefined" || typeof(val) == null) return ''; //check value before process it. 
    return JSON.stringify(val, null, 2) 
     .replace(/ /g, ' ') 
     .replace(/\\n/g, '<br>'); 
    } 
} 

JS 개체, 나는 concat 내가 할 수 있도록 두 개체를 JSON.stingify 또는 부모 내부의 childObj를 추가해야합니다.

enter image description here

var parentJSONObj = JSON.stringify(object) 
var childObj = JSON.stringify(object) // in a diferent schema 
this.output = parentJSONObj.replace(replaceObj, childObj) // and need to replace a property inside childObj 

정도로 this.output 파이프 필터 슬래시 추가 제공 추가 내가 이미 JSON 문자열 생각 최종 JSON 구조이다. 내가 JSON.parse(this.output)를하려고하면 그것은 나에게 CSS 솔루션을 Unexpected token o in JSON at position 214

enter image description here

답변

0

이의 오류입니다 제공 : 나는 작업 plunker 만들어

code { 
    white-space: pre; 
} 

:

https://plnkr.co/edit/wULnv7b3tsKrML6hslWu?p=preview

+0

같은, 내가 plnkr 업데이트와'

{{ x | prettyprint }}
'처럼 JSON을 인쇄하고 지금은 물건을 많이 추가 . https://plnkr.co/edit/ZqOXS30XPTu9ponWFdgZ?p=preview – nCore

+0

대체 기능이 필요한 이유는 무엇입니까? – Bazinga

+0

당신의 플렁커가 현재 작동 중 https://plnkr.co/edit/wdUHPHk6l5h8vY2viddj?p=preview – Bazinga

1

변경을 div 태그 t O pre 태그

<pre [innerHTML]="x | prettyprint"></pre> 

DEMO : https://plnkr.co/edit/bpisrwlf2aFZFteapwY1?p=preview

+0

여전히 동일하지만, plnkr을 업데이트하고 '

{{ x | prettyprint }}
'과 같은 JSON을 인쇄하면 많은 것들이 추가되었습니다. 그러나이 JSON을 텍스트 영역에 넣으므로 편집 가능하므로'pre' 태그에 넣으면 사용자가 편집 할 수 없습니다. https://plnkr.co/edit/ZqOXS30XPTu9ponWFdgZ?p=preview – nCore

+0

https://plnkr.co/edit/pn3SqPEElT7dgtjg4LL6?p=previewn 'textarea'와'pre' 태그로 – micronyks

+0

Pretag없이 Infact도 작동합니다! https://plnkr.co/edit/cLOy1BWjS4NDGGBiMBvs?p=preview – micronyks

3

2 코너에는 내장 JSON 데이터를 포맷하는 파이프. HTML 템플릿을 다음으로 변경하십시오.

<pre>{{ x | json }}</pre> 

사용자 정의 파이프는 단순히 기본 기능을 복제하는 것입니다. 다음은

는 JSON 파이프의 전체 소스입니다 :

@Pipe({name: 'json', pure: false}) 
export class JsonPipe implements PipeTransform { 
    transform(value: any): string { return JSON.stringify(value, null, 2); } 
} 

참조 : https://github.com/angular/angular/blob/master/modules/@angular/common/src/pipes/json_pipe.ts 아직도

+0

그래, 파이프 필터'json'을 넣을 때마다 항상 구조체에'\'을 추가하는 것을 보았습니다. – nCore

+1

그것의 추가 슬래시 나는 그것의 JSON.stringify는 이미 문자열 JSON인데, 그것이 필터가하는 일이라고 생각한다. – nCore

+1

그렇습니다. JSON 문자열을 문자열로 변환하면 슬래시가 생깁니다. 문자열에서 JSON.parse()를 호출 한 다음 JSON 파이프를 통해 전달할 수 있습니다. –