To parse JSON in shell scripts using jq, you can utilize its filtering syntax to extract values from structured data. Start by piping JSON input into jq or specifying a file, such as echo '{"name": "Alice"}' | jq '.name' or jq '.name' data.json, which extracts the value of the "name" key. For nested objects like { "user": { "details": { "name": "Bob" } }}, use dot notation: jq '.user.details.name' data.json. When handling arrays, such as { "users": [ {"name": "Alice"}, {"name": "Bob"} ] }, retrieve all names with jq '.users[].name' data.json, or access a specific element via index: jq '.users[0].name' data.json. To process results further in a script, use the -r flag for raw output and combine fields using string interpolation: jq -r '"Name: $(.user.details.name), Email: $(.user.details.email)"' data.json. With these methods, jq simplifies JSON parsing and manipulation within shell environments.
Parsing JSON in a shell script isn’t straightforward by default, but with jq
, it becomes both easy and powerful. The key is knowing how to structure your command so that you extract exactly what you need from the JSON data.
Basic Syntax for Using jq
The basic way to use jq
is to pipe JSON data into it or specify a file. Here’s the general form:
jq '[filter]' [file]
Or if you're piping data:
echo '{"name": "Alice"}' | jq '.name'
This will output:
"Alice"
You can see that .name
is the filter here — it tells jq
which field to extract.
If you're working with a JSON file (data.json
), you'd do something like:
jq '.name' data.json
Extracting Values from Nested Objects
JSON often contains nested structures. Let's say you have this kind of data:
{ "user": { "id": 123, "details": { "name": "Bob", "email": "bob@example.com" } } }
To get the name, you’d chain keys together:
jq '.user.details.name' data.json
And that would return:
"Bob"
You don't need to write special parsing code — just build the right path using dot notation.
Handling Arrays in JSON
A common case is when a value is inside an array. For example:
{ "users": [ {"name": "Alice"}, {"name": "Bob"} ] }
To get all names:
jq '.users[].name' data.json
That outputs:
"Alice" "Bob"
If you want just the first name:
jq '.users[0].name' data.json
Which gives:
"Alice"
You can also loop over them in a script:
jq -r '.users[].name' data.json | while read name; do echo "User: $name" done
-r
tellsjq
to output raw strings (without quotes).
Formatting Output for Use in Scripts
Sometimes you want clean values without quotes or extra formatting. That’s where the -r
flag comes in handy.
For example:
jq -r '.user.details.name' data.json
Returns:
Bob
Without the quotes — which makes it easier to assign to variables or process further in shell scripts.
Also, if you're combining multiple fields, you can format them using string interpolation:
jq -r '"Name: \(.user.details.name), Email: \(.user.details.email)"' data.json
Output:
Name: Bob, Email: bob@example.com
This makes it simple to generate log lines or messages directly from JSON.
So, basically, once you understand how to navigate the structure with filters, jq
becomes a reliable tool for handling JSON in shell scripts. It's not complicated, but getting the syntax right helps avoid frustration later.
The above is the detailed content of How to parse JSON from a shell script using jq?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The combination of golangWebSocket and JSON: realizing data transmission and parsing In modern Web development, real-time data transmission is becoming more and more important. WebSocket is a protocol used to achieve two-way communication. Unlike the traditional HTTP request-response model, WebSocket allows the server to actively push data to the client. JSON (JavaScriptObjectNotation) is a lightweight format for data exchange that is concise and easy to read.

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

MySQL5.7 and MySQL8.0 are two different MySQL database versions. There are some main differences between them: Performance improvements: MySQL8.0 has some performance improvements compared to MySQL5.7. These include better query optimizers, more efficient query execution plan generation, better indexing algorithms and parallel queries, etc. These improvements can improve query performance and overall system performance. JSON support: MySQL 8.0 introduces native support for JSON data type, including storage, query and indexing of JSON data. This makes processing and manipulating JSON data in MySQL more convenient and efficient. Transaction features: MySQL8.0 introduces some new transaction features, such as atomic

Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string. When writing programs in Golang, we often need to convert the structure into a JSON string. In this process, the json.MarshalIndent function can help us. Implement formatted output. Below we will explain in detail how to use this function and provide specific code examples. First, let's create a structure containing some data. The following is an indication

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

Using PHP's json_encode() function to convert an array or object into a JSON string and format the output can make it easier to transfer and exchange data between different platforms and languages. This article will introduce the basic usage of the json_encode() function and how to format and output a JSON string. 1. Basic usage of json_encode() function The basic syntax of json_encode() function is as follows: stringjson_encod

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

Quick Start: Pandas method of reading JSON files, specific code examples are required Introduction: In the field of data analysis and data science, Pandas is one of the important Python libraries. It provides rich functions and flexible data structures, and can easily process and analyze various data. In practical applications, we often encounter situations where we need to read JSON files. This article will introduce how to use Pandas to read JSON files, and attach specific code examples. 1. Installation of Pandas
