Parsing Nested JSON in Linux
To process nested JSON structures in Linux, you can use various tools and libraries. Here are some popular options:
jq
jq
is a lightweight and flexible command-line JSON processor. It can be used to parse, filter, and transform JSON data. Here's an example of how to use jq
to extract a value from a nested JSON structure:
## Sample JSON data
json_data='{"person": {"name": "John Doe", "age": 30, "address": {"street": "123 Main St", "city": "Anytown", "state": "CA"}}}'
## Extract the value of the "street" key from the nested "address" object
echo $json_data | jq '.person.address.street'
## Output: "123 Main St"
Python's json
module
The standard Python json
module provides functions for parsing and manipulating JSON data. Here's an example of how to parse a nested JSON structure using Python:
import json
## Sample JSON data
json_data = '{"person": {"name": "John Doe", "age": 30, "address": {"street": "123 Main St", "city": "Anytown", "state": "CA"}}}'
## Parse the JSON data
data = json.loads(json_data)
## Access the nested values
print(data['person']['name']) ## Output: "John Doe"
print(data['person']['address']['street']) ## Output: "123 Main St"
Libraries
C: jansson
The jansson
library is a C library for parsing, manipulating, and generating JSON data. Here's an example of how to use jansson
to parse a nested JSON structure:
#include <jansson.h>
#include <stdio.h>
int main() {
const char *json_data = "{\"person\": {\"name\": \"John Doe\", \"age\": 30, \"address\": {\"street\": \"123 Main St\", \"city\": \"Anytown\", \"state\": \"CA\"}}}";
json_t *root = json_loads(json_data, 0, NULL);
json_t *person = json_object_get(root, "person");
json_t *address = json_object_get(person, "address");
printf("Name: %s\n", json_string_value(json_object_get(person, "name")));
printf("Street: %s\n", json_string_value(json_object_get(address, "street")));
json_decref(root);
return 0;
}
These examples demonstrate how to parse and extract values from nested JSON structures using various tools and libraries in a Linux environment. The choice of tool or library will depend on the specific requirements of your project and the programming language you are using.