0

I'm trying to run JQ on a JSON file, through command line from C# code. One of the required arguments includes spaces and quotation marks, so it is itself wrapped between quotation mark. However, this argument is formatted from another string which includes quotations marks:

var jq =  ".data[] | select(.name==\"mytest\") | .id == \"adxd\"";
var psi = new ProcessStartInfo
        {
            FileName = _exe,
            Arguments = $"-c \"{jq}\" {_settings.JSONFile}",
        };

However, the arguments turn out as:

-c ".data[] | select(.name=="mytest") | .id == "adxd"" json.json

Which of course is wrong. It should turn out as:

-c ".data[] | select(.name==\"mytest\") | .id == \"adxd\"" json.json

How can I ensure that the the arguments are decoded correctly with the correct 'levels' of quotation marks?

Ahmad Masalha
  • 379
  • 2
  • 9

1 Answers1

2

Ask yourself: "why are there quotes around the query argument?"

That's because you're adding an escaped quote. The idea here is that writing \" in the "code" renders " in the output.

You're issue is that you need to do this one layer down. You don't want to render the quotes inside the query in C#, you want to render the quotes in the jq.exe application. So you need to work backwards.

  • Inside jp.exe, the value should be ".
  • This means that whatever we send to it (the command line arguments) need to be escaped: \".
  • This means that however we render the command line arguments will need to produce \", and because both of those characters require escaping, you do it.
jq = jq.Replace("\"", "\\\"");

This says "replace all double quotes in my c# string with a backslash and quote" (essentially, just add a backslash before all quotes).

This turns a c# string rendered as abc "def" ghi into abc \"def\" ghi, which is the format your command line argument is expecting.

gunr2171
  • 16,104
  • 25
  • 61
  • 88