Nowadays JSON is everywhere in web app is in configuration files, even in logs. json is the default format used to structure data. And being so common means that there will certainly be times when we will need to process Jason from the command line. could imagine doing this with grep set or other conventional tools, that would be quite a challenge. Luckily for us, there is a command line tool called JK JK Jq dq that we can use to query adjacent files. It comes with its own language syntax, as we'll see in just a few minutes, but first, let's install Jq with the following command sudo apt install Jq.
Now let's use an example file. dummy x is log in JSON format access dot log, which we can also find in the GitHub repository of the course. Let's start with some simple queries Jq dot x dot log will print this command will print the JSON objects back to the screen in a printed format. If you want to grab the request method from each request, we run this command. This will print the request method from each JSON object. Notice the double quotes around each method.
If we want to use the output as input to other scripts, we probably don't want to double code. And that is where the dash r URL output comes in handy. So we use this command. dq is often used for big data queries at a much smaller scale. Say for example, if we want to calculate a statistic of request methods on the log file, we would run the following command. Now we can see a count of get put post and delete requests.
If we want the same type of calculation for another field, say upkeep We can run the next command. Notice the syntax for accessing nested fields is to just use the.as the delimiter between them delimiter delimiter delimiter Yeah, that is the delimiter. Also notice that we are using single codes instead of double code to mark our query as a string. And of course, notice that I'm learning to speak proper English. As you probably know the difference between single and double quotes in shell scripting is that double quoted strings will try to expand variables by a single quoted string will be treated as a fixed string to query for to query all the request bodies we can use this command. But as we see from the output even seems empty request bodies are logged and will be printed by Jq to skip printing empty bodies we can use cues query language to select all document without an empty body like this.
If we want to refine our search even more and only print the first element in the death holds object of the request body we use the following command. We can even perform arithmetic operations with the return value such as incremented it with this command there are many more examples and use cases for Jq but for them, just go to the official page and visit the tutorial there.