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
  • 123
  • 1
  • 5
  • 1
    [This](https://stackoverflow.com/questions/14339701/c-sharp-process-start-needs-arguments-with-double-quotes-they-disappear) should help but I'm trying to find something better. – gunr2171 Jan 26 '22 at 13:39
  • 1
    You need to escape the \. ==\\\"mytest\\\". – mwe Jan 26 '22 at 13:42
  • I can't help but wonder why you opted to use jq for this? – DiplomacyNotWar Jan 26 '22 at 13:48
  • I'm open for other suggestions @Llama! My modest research brought me to https://stedolan.github.io/jq/ – Ahmad Masalha Jan 26 '22 at 13:56
  • 1
    Perhaps the .NET library JSON.NET? – DiplomacyNotWar Jan 26 '22 at 13:58
  • It does not support the functionality I need. I need to be able to run user-provided queries on some json. With JSON.NET the user would have to write actual code as input, rather than simple commands such as in the link I provided. (Unless I missed something) – Ahmad Masalha Jan 26 '22 at 14:04

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
  • 12,476
  • 25
  • 58
  • 80