Search code examples
pythonyaml

How to read "\'-alert(1)//" using PyYAML?


In yaml file, there is a string:

"\'-alert(1)//"

I used the following code to read the file:

with open(file_path, 'r') as file:
        yaml_data = yaml.safe_load(file) # also tried unsafe_load

I got the error message:

found unknown escape character "'"

How can I read this string successfully?


Solution

  • You can use the backslash to escape some special characters in double quoted scalars in YAML, but the single quote is not an escapable character. Therefore your YAML is invalid.

    Either escape the backslash ( "\\'-alert(1)//" ) or remove the double quotes ( \'-alert(1)// ) for the same result after loading. You can also remove the backslash ( "'-alert(1)//" ), which loads to a different result.