简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM