使用拉梅尔亚姆勒,如何使带有换行符的变量成为多行而不带引号

2024-10-03 21:34:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在生成一个用作协议的YAML,其中包含一些生成的JSON。在

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

然后我得到这个输出

^{pr2}$

对我来说,这看起来会更好 如果我能够使多行行以管道|开始格式化

我想看到的输出是

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

看看这是多么容易阅读。。。在

那么如何用python代码解决这个问题呢?在


Tags: thesampleimportidjsonyamltypeaccount
1条回答
网友
1楼 · 发布于 2024-10-03 21:34:49

您可以:

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

它给出了:

^{pr2}$

注意事项:

  • 由于您使用的是普通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=(',', ': ')))
    

    在这种情况下,您不需要调用walk_tree()


即使您仍在使用python2,您也应该开始习惯使用print函数而不是print语句。在每个Python文件的顶部包括:

from __future__ import print_function

相关问题 更多 >