Json file using "contents"

Is it possible to write a json file using the contents keyword? I first tried the following:

"samples-json": {
        "basename": "samples_json.json",
        "class": "File",
        "contents": {"R": "R1", "sex": "Unknown"}
    },

But I received this error:

the `contents` field is not valid because value is a CommentedMap, expected null or string

I then tried it as a string, while escaping the internal quotes in the json:

"samples-json": {
        "basename": "samples_json.json",
        "class": "File",
        "contents": "{\"R\": \"R1\", \"sex\": \"Unknown\"}"
},

But then the quotes are also escaped inside of the resulting json file, and the contents of the file are interpreted as a single string by the tool (which opens it using json.load(open("samples_json.json")).

What would be the proper way to escape the double quotes in the inputs file, while leaving them unescaped in the dynamically-generated one?

Hey Ian,

It sounds like something else might be going on and I suspect it is within the tool/script you mentioned. When I run this on my system (v3.1.20210518233432) the json file is properly formatted and contains no escaped quotes.

Here’s the CWL I used to test. I had trouble getting cwltool to produce samples_json.json in a context where I could directly open it, so instead I used xxd to be sure that my shell wasn’t automatically unescaping anything:

cwlVersion: v1.2
class: CommandLineTool

baseCommand: xxd

inputs:
  file:
    type: File
    inputBinding:
      position: 0

stdout: stdout.txt

outputs:
  xxd_result:
    type: stdout

And the configuration file:

"file": {
        "basename": "samples_json.json",
        "class": "File",
        "contents": "{\"R\": \"R1\", \"sex\": \"Unknown\"}"
}

Executed with the command line:

cwltool test.cwl test.json

Hope this helps,
-Alex