Reputation: 147
I have some JSON data:
{
"key1":"value1",
"key2":"value2",
"HTTP Method": "POST",
"key3":{
"key3_1":"value3_1",
"key3_2":"value3_2",
"key3_3":"value3_3",
"key3_4":"value3_4",
"key3_5":"value3_5",
"key3_6":"value3_6",
"key3_7":"value3_7"
},
"key4":{
"Accept":[
"*/*"
]
}
}
I want to do two operations here:
"value3_5"
to "val****"
.In the second case, I can use this logic : If s
is your string and n
the number of not hidden characters: s[:n] + '*' * (len(s)-n)
.
All I want to do is:
{
"key1":"value1",
"key2":"value2",
"httpMethod":"POST",
"key3":{
"key3_1":"value3_1",
"key3_2":"val*****",
"key3_5":"value3_5",
"key3_7":"val*****"
},
"key4":{
"Accept":[
"*/*"
]
}
}
I have removed here some nested key value pair and change the nested value to "value3_2"
to "val*****"
(the 2nd part was already done.)
Upvotes: 0
Views: 82
Reputation: 2692
Here are two functions to do these operations. First one takes key/nested_key
name and delete it from data, while the second one takes key/suffix
and replace it with stars:
data = {
"key1":"value1",
"key2":"value2",
"HTTP Method": "POST",
"key3":{
"key3_1":"value3_1",
"key3_2":"value3_2",
"key3_3":"value3_3",
"key3_4":"value3_4",
"key3_5":"value3_5",
"key3_6":"value3_6",
"key3_7":"value3_7"
},
"key4":{
"Accept":[
"*/*"
]
}
}
def remove_nested_key_pair(key_name, nested_key_name):
global data
# Remove by key_name and nested_key_name
data[key_name].pop(nested_key_name, None)
return data
def replace_by_suffix(key_name, suffix):
global data
for i, v in data[key_name].items():
# check whether suffix is at the end of any value
# if yes replace it with 'val*****'
if suffix == v[len(v) - 3:]:
data[key_name][i] = 'val*****'
return data
So when you call above functions like this:
data = remove_nested_key_pair('key3', 'key3_3')
data = remove_nested_key_pair('key3', 'key3_4')
data = remove_nested_key_pair('key3', 'key3_6')
data = replace_by_suffix('key3', '3_2')
data = replace_by_suffix('key3', '3_7')
The result will look like below:
{
'key1': 'value1',
'key2': 'value2',
'HTTP Method': 'POST',
'key3': {
'key3_1': 'value3_1',
'key3_2': 'val*****',
'key3_5': 'value3_5',
'key3_7': 'val*****'},
'key4': {'Accept': ['*/*']}
}
Upvotes: 1