Practical JSON Data Manipulation
Beyond simply extracting data, there are various ways to manipulate JSON data in Linux. Here are some common operations and examples:
Filtering JSON Data
You can use jq
to filter JSON data based on specific criteria. For example, to extract all the names from a list of people:
json_data='[
{"name":"John Doe","age":30,"email":"[email protected]"},
{"name":"Jane Smith","age":25,"email":"[email protected]"},
{"name":"Bob Johnson","age":40,"email":"[email protected]"}
]'
echo $json_data | jq '.[].name'
You can use jq
to transform the structure of JSON data. For example, to extract the email addresses and ages into a new object:
echo $json_data | jq '[{email: .email, age: .age}]'
Updating JSON Data
You can use jq
to update the values in a JSON object. For example, to change the age of a person:
echo $json_data | jq '.[0].age = 31'
Merging JSON Data
You can use jq
to merge multiple JSON objects into a single object. For example, to combine two JSON objects:
obj1='{"name":"John Doe","age":30}'
obj2='{"email":"[email protected]","city":"Anytown"}'
echo "$obj1 $obj2" | jq -s add
These are just a few examples of the many ways you can manipulate JSON data in Linux using tools like jq
. By understanding these techniques, you can effectively work with JSON data in your Linux-based projects and applications.