scalar with `\\n` will be parsed to new line

Issue #1076 invalid
Kun Li created an issue

This is a test to demonstrate the problem, If a scalar contains a substring `\\n`, it's not a new line, but it's parsed to a newline in a scalar.

    @Test
    void snakeYamlTest() {
        String source = """
          "a" : "b\\nc"
          """;
        StringReader reader = new StringReader(source);

        StreamReader streamReader = new StreamReader(reader);
        Scanner scanner = new ScannerImpl(streamReader, new LoaderOptions());
        Parser parser = new ParserImpl(scanner);

        List<String> scalars = new ArrayList<>();
        for (Event event = parser.getEvent(); event != null; event = parser.getEvent()) {
            if (event.getEventId() == org.yaml.snakeyaml.events.Event.ID.Scalar) {
                ScalarEvent scalar = (ScalarEvent) event;
                String scalarValue = scalar.getValue();
                scalars.add(scalarValue);
            }
        }

        assertThat(scalars.size()).isEqualTo(2);
        assertThat(scalars.get(0)).isEqualTo("a");
        assertThat(scalars.get(1)).isEqualTo("b\\nc");

        // expected:
        //  "b\nc"
        // but was:
        //  "b
        //  c"
    }

Comments (7)

  1. Andrey Somov

    Found the answer:

    This is the only scalar style capable of expressing arbitrary strings, by using escape sequences.

    The double backslash (\\) in the source becomes a single slash in the input string. And that is why \n is translated to the new line.

    As designed.

  2. Log in to comment