h0llym0lly
h0llym0lly

Reputation: 71

Sed values from JSON Array

I am trying to change values from array in a JSON object with sed and jq. So object looks like this:

{
  "alertrulemethoddata": "",
  "alertruleimportance": 50,
  "alertruletype": "any",
  "alertrule_any": "filter:\n- query_string:\n       query: 'data.win.system.eventID:\"4624\"'",
  "alertrulemethodusers": [],
  "alertrulemethod": "none",
  "alertruleindexpattern": "windows",
  "alertruleplaybooks": [],
  "alertrulefilename": "windows_logon",
  "alertrulename": "windows-logon",
  "enable": "Y",
  "selectedroles": [
    "admin"
  ],
  "alertruleriskkeyaggregation": "MAX",
  "authenticator": "index",
  "alertruleriskkey": "",
  "changed": false
}

And I am trying to change value from field "selectedroles" to a script argument. What I did so far:

for i in `cat $file`; do

    selectedroles=`echo "$i" | jq '._source.selectedroles' | tr -d "[]" | tr -d "\"" | tr -d "\n" | tr -d " "`
    for j in $selectedroles; do
      sed -i 's/\"selectedroles\":[\"'$j'\"]/\"selectedroles\":[\"'$newname'\"]/g' $file
    done

done

Could someone help me with this problem? I am struggling with this for long time and have no clue what is the issue.

Upvotes: 0

Views: 645

Answers (1)

Léa Gris
Léa Gris

Reputation: 19625

Modify the array directly with jq:

#!/usr/bin/env bash

# Change the selected roles from JSON file
# @params
# $1: The JSON File Path/Name
# $@: Following arguments to replace selectedroles
new_selectedroles () {
  # Get file name argument
  json_file="$1"

  # Remove file-name but keep remaining arguments
  shift

  # Make a temporary file to store the processed JSON
  tmp_json="$(mktemp)"

  # Replace selectedroles array content with remaining arguments
  jq '.selectedroles=$ARGS.positional' "$json_file" --args "$@" >"$tmp_json"

  # Replace the JSON file by its modified version
  mv -- "$tmp_json" "$json_file"
}

# Example Usage:
new_selectedroles a.json hello world

Content of JSON file after running Example Usage:

{
  "alertrulemethoddata": "",
  "alertruleimportance": 50,
  "alertruletype": "any",
  "alertrule_any": "filter:\n- query_string:\n       query: 'data.win.system.eventID:\"4624\"'",
  "alertrulemethodusers": [],
  "alertrulemethod": "none",
  "alertruleindexpattern": "windows",
  "alertruleplaybooks": [],
  "alertrulefilename": "windows_logon",
  "alertrulename": "windows-logon",
  "enable": "Y",
  "selectedroles": [
    "hello",
    "world"
  ],
  "alertruleriskkeyaggregation": "MAX",
  "authenticator": "index",
  "alertruleriskkey": "",
  "changed": false
}

Upvotes: 1

Related Questions