Skip to content

Instantly share code, notes, and snippets.

@amitkrout
Created February 15, 2022 18:14
Show Gist options
  • Select an option

  • Save amitkrout/1feff0ba23e6e1a018d005200788ccfa to your computer and use it in GitHub Desktop.

Select an option

Save amitkrout/1feff0ba23e6e1a018d005200788ccfa to your computer and use it in GitHub Desktop.
def findkeysvalues(inputDict, key):
if isinstance(inputDict, list):
for i in inputDict:
for x in findkeysvalues(i, key):
yield x
if isinstance(inputDict, dict):
if key in inputDict:
yield inputDict[key]
for j in inputDict.values():
for x in findkeysvalues(j, key):
yield x
def process_JSON_value(jsonFileInput, parentInputKey, key):
with open(jsonFileInput) as jsonFile:
data = json.load(jsonFile)
Dict = { }
for i in data:
if i == parentInputKey:
Dict[i] = data[i]
return list(findkeysvalues(Dict, key))
def createRulesJSON():
Dict = { }
Dict['tire1'] = {}
Dict['tire6'] = {}
with open("test1.json") as jsonFile:
data = json.load(jsonFile)
countsource = 0
countdest = 0
countport = 0
rules_items_source = findkeysvalues(data, "source")
for i in rules_items_source:
x = re.findall("\w+", i[0])
items = process_JSON_value("test.json", x[0], "compname")
if countsource == 0:
Dict['tire1']['source'] = items
else:
Dict['tire6']['source'] = items
countsource = countsource + 1
rules_items_dest = findkeysvalues(data, "dest")
for i in rules_items_dest:
x = re.findall("Microservice.\w+", i[0])
y = x[0].split(".")
items = process_JSON_value("test.json", y[0], y[1])
if countdest == 0:
Dict['tire1']['dest'] = items
else:
Dict['tire6']['dest'] = items
countdest = countdest + 1
rules_items_port = findkeysvalues(data, "port")
for i in rules_items_port:
if countport == 0:
Dict['tire1']['port'] = items
else:
Dict['tire6']['port'] = items
countport = countport + 1
with open("sample.json", "w") as file:
json.dump(Dict, file)
createRulesJSON()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment