Search code examples
pythonjsonshellsh

Required shell script to modify json data


I am new to shell scripting, I need help in converting python code to shell script.


# Your JSON data
data = {
    "group1": [
        {"key1": "val1", "key2": "val2", "key3": "val3", "key4": "val4"},
        {"key1": "bval1", "key2": "val2", "key3": "bval3"},
        {"key1": "bval1", "key2": "xval2", "key3": "bval3", "key4": "bval4"},
    ],
    "group2": [
        {"key1": "zval1", "key2": "val2", "key3": "zval3"},
        {"key1": "zbval1", "key2": "zval2", "key3": "zval3"},
        {"key1": "bval1", "key2": "xval2", "key3": "bval3"},
    ],
}

# Function to append ",test" to "key3" and "key4" values if "key2" is "val2"
def append_value(group):
    for item in group:
        if item.get("key2") == "val2":
            item["key3"] = item.get("key3", "") + ",test"
            if "key4" in item:
                item["key4"] = item["key4"] + ",test"

# Iterate through each group and append values
for group_name, group_data in data.items():
    append_value(group_data)

# Print the updated JSON
print(json.dumps(data, indent=4))

Above program updates the json.

The conditions are:

  1. Update key3 and Key4 to "test" no matter which group they belong.
  2. Skip if key4 is not present.
  3. Update should happen only if key2 value is val2 in that group.

Please help me preparing the shell script meeting above conditions.

Thanks in advance.


Solution

  • #!/bin/bash
    
    # Your JSON data
    json_data='
    {
        "group1": [
            {"key1": "val1", "key2": "val2", "key3": "val3", "key4": "val4"},
            {"key1": "bval1", "key2": "val2", "key3": "bval3"},
            {"key1": "bval1", "key2": "xval2", "key3": "bval3", "key4": "bval4"}
        ],
        "group2": [
            {"key1": "zval1", "key2": "val2", "key3": "zval3"},
            {"key1": "zbval1", "key2": "zval2", "key3": "zval3"},
            {"key1": "bval1", "key2": "xval2", "key3": "bval3"}
        ]
    }'
    
    # Update key3 and key4 values meeting the conditions
    updated_json=$(echo "$json_data" | jq '
        .[] |= map(
            if .key2 == "val2" then
                .key3 += ",test"
                | if has("key4") then .key4 += ",test" else . end
            else
                .
            end
        )
    ')
    
    # Print the updated JSON
    echo "$updated_json"