Search code examples
jsonoutputjqdata-objects

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


Goal:

  • Search the keys actual name value for a string or set of strings
  • search using case insensitive values
  • return the object(s) containing the values

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


Solution

  • 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"))'