I have been looking for a solution to my problem for a few hours.
Do you know a method or an algorithm to achieve the following?
#Input
text1 = "network.routes.vlan[0].address"
val1 = "value1"
text2 = "network.routes.vlan[1].address"
val2 = "value2"
text3 = "network.routes.vlan[2].address"
val3 = "value3"
text3 = "network.interface.name"
val3 = "name_interface"
merge_variables_to_unique_object()
#Output
[{
network: {
routes : {
vlan: [
{
address: value1
},
{
address: value2
},
{
address: value3
}
]
},
interface: {
name: name_interface
}
}
}]
Thank you very much in advance!
CodePudding user response:
To do this, I would make an array of all of the values
values = [[text1, val1], [text2, val2], [text3, val3], [name, name_interface]]
# name and name_interface are the last two values
Then, I would make the function take a list of values and create a base dictionary for adding values into.
def merge_variables_to_unique_object(values: list):
base_json = {
"network": {
"routes": {
"vlan": [
]
},
"interface": {
}
}
}
After that, it's just a simple for loop that goes until the length of the values array. Inside of the array, you check if you are at the last element of the array. If you are not at the end, you add the values to the array (remember that vlan is a dictionary)
base_json["network"]["routes"]["vlan"].append({values[i][0]: values[i][1]})
If you are at the last element of the array, you add the values to interface:
base_json["network"]["interface"][values[i][0]] = values[i][1]
The for loop would look like this:
for i in range(len(values)):
if i < len(values) - 1:
base_json["network"]["routes"]["vlan"].append({values[i][0]: values[i][1]})
else:
base_json["network"]["interface"][values[i][0]] = values[i][1]
Afterwards, you would just return base_json because it was changed inside of the for loop.
CodePudding user response:
If you want all the content in this syntactical format you can simply write it to an file or an string. Either way it will be something like this. This is manually creating the syntax you want that you can write to an file to force through .json.
input1 = text1.split(".")
input2 = text2.split(".")
and so on
str1="[{\n\tinput1[1]: {\n\t\tinput1[2] : {\n\t\t\tinput1[3]"
in this fashion
\t are tabs like indenting in code
\n is interpreted in strings as next line.
Is this helpful?
