codelinx
codelinx

Reputation: 137

JSON How to search keys name value and print the objects that contains a string or set of strings with case insensitivity?

Goal:

Un-sanitized test data:

{
    "PassworD": "dashnd8",
    "Name": "Katy"
}
{
    "PasSWOrd": "DJNAS98das98",
    "Name": "Paulo"
}
{
    "Pa$$word": "H(AD*Sn",
    "Name": "Crissy"
    
}
{
    "PW": "nA(*DS",
    "Name": "Jamel"
    
}
{
    "pW": "0d9asm0i",
    "Name": "Denny"
}

sanitized test data:

{
    "Password": "PW",
    "Name": "Katy"
}
{
    "Password": "pW",
    "Name": "Paulo"
}
{
    "Password": "pw",
    "Name": "Crissy"
    
}
{
    "Password": "passWorD",
    "Name": "Jamel"
    
}
{
    "Password": "PAssword",
    "Name": "Denny"
}

Note: if the json object has a different Hierarchy please add the necessary steps to access your data

Upvotes: 0

Views: 1153

Answers (2)

peak
peak

Reputation: 117027

To sanitize a stream of objects efficiently:

with_entries( if .key | ascii_downcase | IN("password", "pw", "pa$$word")
              then .key="Password" 
              else . end) 

To select efficiently, without sanitizing the results:

select( any(keys_unsorted[] | ascii_downcase;
            IN("password", "pw", "pa$$word") ) )

Upvotes: 0

codelinx
codelinx

Reputation: 137

To satisfy the search we will use the following:

  • select(): pick the key that we will be selecting to search explicitly
  • ascii_downcase: this modifier is helpful for these type of searches where you do not know if the key has a a certain value. This will remove case sensitivity i.e. Tom vs tOm vs toM etc
  • contains(): help search for multiple values

jq 'select( keys[]| ascii_downcase |contains( "pw","password"))'

BONUS:

However another search might be if you want to search the values based on a specific key in more structured sanitized data where the key name is explicitly the same you would be able to search the values by do this ->

jq 'select( .Password| ascii_downcase |contains( "pw","password"))'

Upvotes: -1

Related Questions