In this section, we'll walk through some hands-on examples of transforming JSON data using the tools and techniques we've discussed earlier.
Example 1: Extracting and Filtering JSON Data with jq
Let's start with a simple example of using jq
to extract and filter JSON data. Suppose we have the following JSON data:
{
"name": "John Doe",
"age": 30,
"email": "[email protected]",
"hobbies": ["reading", "hiking", "photography"],
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip": "12345"
}
}
We can use jq
to extract specific fields from this JSON data:
echo '{"name": "John Doe", "age": 30, "email": "[email protected]", "hobbies": ["reading", "hiking", "photography"], "address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zip": "12345"}}' | jq '.name, .email, .address.city'
Output:
"John Doe"
"[email protected]"
"Anytown"
We can also use jq
to filter the JSON data based on certain conditions:
echo '{"name": "John Doe", "age": 30, "email": "[email protected]", "hobbies": ["reading", "hiking", "photography"], "address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zip": "12345"}}' | jq '.hobbies[] | select(. == "hiking")'
Output:
"hiking"
Now, let's use json-cli
to transform the same JSON data:
echo '{"name": "John Doe", "age": 30, "email": "[email protected]", "hobbies": ["reading", "hiking", "photography"], "address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zip": "12345"}}' | json-cli transform --template '{"fullName": .name, "ageInYears": .age, "interests": .hobbies}'
Output:
{
"fullName": "John Doe",
"ageInYears": 30,
"interests": ["reading", "hiking", "photography"]
}
Finally, let's use Python's json
module to transform the JSON data:
import json
## Load JSON data
data = '{"name": "John Doe", "age": 30, "email": "[email protected]", "hobbies": ["reading", "hiking", "photography"], "address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zip": "12345"}}'
json_data = json.loads(data)
## Transform the data
transformed_data = {
"full_name": json_data["name"],
"age_in_years": json_data["age"],
"interests": json_data["hobbies"]
}
## Dump the transformed data to JSON
transformed_json = json.dumps(transformed_data, indent=2)
print(transformed_json)
Output:
{
"full_name": "John Doe",
"age_in_years": 30,
"interests": ["reading", "hiking", "photography"]
}
These examples should give you a good starting point for working with JSON data transformation in your Linux-based projects. Remember, these are just a few of the many techniques and tools available, and you can further explore and combine them to suit your specific needs.