.NET/C#: Small command-line tool to query REST JSON results from a batch file.
Posted by jpluimers on 2023/08/29
Often the power is in the combinations of tools.
Read until the epilogue…
Prologue
In this case, I needed to be able to query the JSON results of calls to REST services from the command-line so I could process them in Batch files.
Since I could not find anything readily available, I originally Originally I opted for the PowerShell command-line scripting tool, as that ships with recent Windows versions and can re-use anything that .NET brings. But though [Wayback/Archive] .NET has built in JSON serialization support, there is [Wayback/Archive] no querying support in it.
Then I thought about Delphi, as it [Wayback/Archive] too has a built-in JSON parser, but even the well known [Wayback/Archive] JSON SuperObject library has no query support.
Back to .NET, which – like Delphi – has a well known and respected third party JSON library as well: [Wayback/Archive] NewtonSoft JSON aka JSON.net and that one [Wayback/Archive] does have support for querying JSON with the SelectToken function.
That’s the fundament of the rest of this article, with the potential to be used in a cross-platform as well.
So no need for a plan B.
Eventually, I might still execute Plan B, as the underlying XPath query language has a more powerful expression engine than SelecToken currently has. But I might as well look into [W/A] JSONiq as well.
This is plan B:
- deserialize JSON into objects
- serialize them into XML
- perform XPath on the XML
The JSON command-line query tool
Finally, I wanted the tool to be a single-file executable. This is unlike normal .NET executables that depend on external assemblies. So I needed to link in the JSON.net assembly and others into one. The process uses [W/A] ILMerge and is described at [W/A] Visual Studio Merging of Assemblies After Build | noob=>boss.
Epilogue
Just when you finished a nice piece of work, you [Wayback/Archive] find out that someone else did an even better job: [Wayback/Archive] jq:
jqis a lightweight and flexible command-line JSON processor.
jqis likesedfor JSON data – you can use it to slice and filter and map and transform structured data with the same ease thatsed,awk,grepand friends let you play withtext.jqis written in portable C, and it has zero runtime dependencies.
Oh well (:
--jeroen
PS: I forgot scheduling this post when originally writing it in 2014, but I still think it is worth it after all these years to be published in 2023.
Reference [Wayback/Archive] How to parse a JSON file to variables with the windows command line? – Stack Overflow (thanks [Wayback/Archive] Kriem, and [Wayback/Archive] Idan Arye)






Leave a comment