Developers' Forum

new-lines in json output

new-lines in json output

by Jim Newton -
Number of replies: 2

I'd like to ask that the documentation be clarified on a confusing point.

According to several sources, including https://stackoverflow.com/questions/42068/how-do-i-handle-newlines-in-json, json format does not support imbedded newline characters.    However, the example in section 9.1 (https://coderunner.org.nz/mod/book/view.php?id=198&chapterid=820) implies such is indeed supported.  In the example, the python code (without much explanation) simply prints new line characters (without escaping them) into a string which is later interpolated into the string printed to stdout.  The implication is this is the correct way to achieve newlines in the output of a custom grader.

What should be clarified unambiguously in the documentation (in my opinion) is exactly what needs to be printed to stdout.  Should the output contain newline characters or should they contain a backslash followed by an n?

Of course anyone interested can experiment to find out, but it would be better, in my opinion, that the documentation explain this explicitly.




In reply to Jim Newton

Re: new-lines in json output

by Richard Lobb -

I admit that the documentation does sometimes assume a knowledge of Python. If you're going to do much with CodeRunner, I would recommend learning Python as it does simplify writing of templates.

I've added the following clarification after the program, which I hope answers your question:

Note that in the above program the Python *dictionary*

    {'got': got, 'comment': comment, 'fraction': mark / 5}

gets converted by the call to json.dumps to a JSON object string, which looks syntactically similar but is in fact a different sort of entity altogether. You should always use json.dumps, or its equivalent in other languages, to generate a valid JSON string, handling details like use of the correct quotation marks and escaping of embedded newlines.

By the way, I notice you're reading the version 3.3.0 documentation, in Moodle Book format. Unless you are running an old version of CodeRunner, I'd recommend reading the most recent documentation (version 3.7.5 as of today): see the first link in the main menu on this site.

In reply to Richard Lobb

Re: new-lines in json output

by Jim Newton -

Thanks for the very useful comments.  And yes, I was reading 3.3.0 documentation as I didn't see the more recent documentation link.  Thanks for bringing my attention to this.