2017-05-19 17 views
1

프로토콜로 작동하는 YAML을 생성 중이며 그 안에 생성 된 JSON이 일부 포함되어 있습니다.ruamel.yaml을 사용하면, NEWLINE을 여러 줄로 묶어 따옴표없이 여러 줄로 만들 수 있습니다.

import json 
from ruamel import yaml 
jsonsample = { "id": "123", "type": "customer-account", "other": "..." } 
myyamel = {} 
myyamel['sample'] = {} 
myyamel['sample']['description'] = "This example shows the structure of the message" 
myyamel['sample']['content'] = json.dumps(jsonsample, indent=4, separators=(',', ': ')) 
print yaml.round_trip_dump(myyamel, default_style = None, default_flow_style=False, indent=2, block_seq_indent=2, line_break=0, explicit_start=True, version=(1,1)) 

그때 나는 파이프 |

출력부터 시작하여 여러 행을 포맷 할 수 있다면 훨씬 더 을 볼 수 있었다 나에게

%YAML 1.1 
--- 
sample: 
    content: "{\n \"other\": \"...\",\n \"type\": \"customer-account\",\n \"\ 
    id\": \"123\"\n}" 
description: This example shows the structure of the message 

지금이 출력을 얻을 내가보고 싶은 것은 이것이다.

%YAML 1.1 
--- 
sample: 
    content: | 
    {  
     "other": "...", 
     "type": "customer-account", 
     "id": "123" 
    } 
description: This example shows the structure of the message 

이것이 얼마나 쉽게 읽을 수 있는지보십시오 ...

그래서 어떻게 이것을 파이썬 코드로 해결할 수 있습니까?

+0

YAML 파일이 완전히 동일하지 않습니다. '|'를 사용해야하기 때문에 (''strip * block chomping indicator ''와 함께 블록 스타일을 사용하라.) (http :// /yaml.org/spec/1.2/spec.html#id2794534) – Anthon

답변

0

당신은 할 수 있습니다 :

import sys 
import json 
from ruamel import yaml 

jsonsample = { "id": "123", "type": "customer-account", "other": "..." } 
myyamel = {} 
myyamel['sample'] = {} 
myyamel['sample']['description'] = "This example shows the structure of the message" 
myyamel['sample']['content'] = json.dumps(jsonsample, indent=4, separators=(',', ': ')) 

yaml.scalarstring.walk_tree(myyamel) 

yaml.round_trip_dump(myyamel, sys.stdout, default_style = None, default_flow_style=False, indent=2, block_seq_indent=2, line_break=0, explicit_start=True, version=(1,1)) 

주는 :

%YAML 1.1 
--- 
sample: 
    description: This example shows the structure of the message 
    content: |- 
    { 
     "id": "123", 
     "type": "customer-account", 
     "other": "..." 
    } 

일부 노트 :

  • 당신이 정상 DICT 당신 ​​YAML이 인쇄되는 순서를 사용하고 있기 때문에 구현과 키에 따라 다릅니다. 당신이 순서는 과제에 고정 할 경우 사용

    myyamel['sample'] = yaml.comments.CommentedMap() 
    
  • 당신이 반환 값을 인쇄하는 경우, print(yaml.round_trip_dump)을 사용하지에 쓸 수있는 스트림을 지정 안, 즉 더 효율적입니다.
  • walk_tree은 줄 바꿈이있는 모든 문자열을 스타일 모드를 재귀 적으로 차단하도록 변환합니다. 당신은 명시 적으로 수행 할 수 있습니다

    myyamel['sample']['content'] = yaml.scalarstring.PreservedScalarString(json.dumps(jsonsample, indent=4, separators=(',', ': '))) 
    

    이 경우 당신은 여전히 ​​파이썬 2에서 작업하더라도 walk_tree()


, 당신이 사용하기 시작해야 호출 할 필요는 없다 print 문 대신 print 함수를 사용하십시오. 각 파이썬 파일의 맨 위에 포함 된 내용은 다음과 같습니다.

from __future__ import print_function 
+0

그게 정말 도움이 되었어요. 고마워요! –

+0

@TobiasEriksson이게 문제를 해결했다면,이 대답을 받아 들일만한 것으로 표시하십시오. 저의 평판을 얻는 것 외에도, 그렇게하는 것의 일부는 다른 사람들에게 당신의 질문에 답하는 것입니다 (이 페이지의 주석으로 스크롤하지 않고 검색 할 때도) – Anthon