2017-05-19 1 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 

これがどれくらい簡単に読みやすいかを確認してください...

これをどうすればPythonコードで解決できますか?

+0

あなたのYAMLファイルは完全に同じではありません。 '|'を使うべきであるということを取り除くために、 '| * 'を使用するので、最後の'} 'の後ろに改行が1つあります(つまり、[* strip * block chomping indicator] /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改行を含むすべての文字列をスタイルモードを再帰的にブロックするように変換します。あなたはまた、明示的に行うことができます。

    あなたはまだPythonの2に取り組んでいるにもかかわらず、あなたが慣れる開始する必要がありますwalk_tree()


を呼び出す必要はありません、その場合には

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

printステートメントの代わりにprint関数を使用します。あなたのPythonファイルの先頭にインクルードする場合:

from __future__ import print_function 
+0

これは本当に役に立ちました。ありがとうございました! –

+0

@TobiasErikssonこの問題が解決した場合は、この回答に同意してください。そうすることの一部は、あなたの質問に答えていることを他の人に示していることです(このページのコメントにスクロールせずに、また検索するときも) – Anthon

関連する問題