1

I'm writing a Python script that creates a YAML file according to DataFrame and I came across this:

test:
   query: |
      create or replace view emp as

      select e.id as emp_id
      from employees as e

vs

test:
   query: "create or replace view emp\nas\nselect e.id\
    \                        as emp_id\n       FROM employees\n
   as e\
   \n;"

Are they technically the same or am I missing something? If they are not the same, how do I make the second version like the first that uses a vertical bar.

Anthon
  • 69,918
  • 32
  • 186
  • 246
jun
  • 142
  • 6
  • Does this answer your question? [What is the use of the pipe symbol in YAML?](https://stackoverflow.com/questions/15540635/what-is-the-use-of-the-pipe-symbol-in-yaml) – Alexander May 23 '22 at 08:13

1 Answers1

1

They are technically not the same, but they are similar, as you can see by loading them:

import ruamel.yaml

yaml = ruamel.yaml.YAML(typ='safe', pure=True)
for fn in 'literal.yaml', 'quoted.yaml':
    data = yaml.load(Path(fn))
    print(repr(data['test']['query']))

which gives:

'create or replace view emp as\n\nselect e.id as emp_id\nfrom employees as e\n'
'create or replace view emp\nas\nselect e.id                        as emp_id\n       FROM employees\n as e\n;'

The double quoted style can represent any string using backslash escapes, but is not always very readable.

If you have a string with just linebreaks, you can often use the first form, called a literal style scalar.

You can create individual literal style scalars using the following (of course you don't have to start from loaded data, you can just as well create that in YAML):

import sys
import ruamel.yaml
from ruamel.yaml.scalarstring import LiteralScalarString as LS

yaml = ruamel.yaml.YAML()
data = yaml.load(Path('quoted.yaml'))
data['test']['query'] =  LS(data['test']['query'])
yaml.dump(data, sys.stdout)

which gives:

test:
  query: |-
    create or replace view emp
    as
    select e.id                        as emp_id
           FROM employees
     as e
    ;
Anthon
  • 69,918
  • 32
  • 186
  • 246
  • is there a way to remove the "-" after "|" ? such that it looks something like this query: | – jun May 27 '22 at 07:49
  • 1
    @jun That dash after the pipe is the standard YAML chomping operator. It is there because the string loaded from the second example doesn't end in a newline but in a semicolon `;`. Add something like `if data['test']['query'][-1] != '\n': data['test']['query'] += '\n'` – Anthon May 27 '22 at 08:43