So I have been trying to build out a dynamic JSON library with python recently, and I'm having problems with looping through data. This problem is likely an easy fix but I am very new to programming and especially new to working with JSON.
Basically, I am trying to come out with a JSON output that looks similar to this:
{
"src_host": [
"list item 1",
[
"SSH",
"Telnet",
"STMP"
]
]
},
{
"src_host": [
"list item 2",
[
"SSH",
"Telnet",
"STMP"
]
]
}
I want to populate every "src_host" list with a single entry from another list. I basically want to have a src_host defined for every list item that is being provided. The code I am using is as shown below:
host_dict = {}
host_dict["src_host"] = []
host_services_list = ["SSH","Telnet","STMP"]
mylist = ["list item 1", "list item 2"]
counter = 0
for item in mylist:
json_data['zone'][0]['hosts'].append(host_dict)
host_dict['src_host'].append(mylist[counter])
counter = counter + 1
host_dict['src_host'].append(host_services_list)
The issue I am running into seems to be with the loop I have made to populate the Json data. For a reason I cannot figure out, when I execute this code, the Json output comes out like so:
{
"src_host": [
"list item 1",
"list item 2",
[
"SSH",
"Telnet",
"STMP"
]
]
},
{
"src_host": [
"list item 1",
"list item 2",
[
"SSH",
"Telnet",
"STMP"
]
]
}
As you can see, the list items "list item 1" and "list item 2" are appended to each src_host list, rather than "list item 1" being added to the first src_host and "list item 2" being added to the second.
I'm assuming my logic is flawed here or I'm missing something super simple, but I can't seem to get past this one problem at the moment and wanted to reach out for assistance.
Thank you for any and all help!
Note: The ['zone'][0]['hosts'] is because this portion of Json is a small piece in a larger Json file. I didn't think it was necessary to show every bit of the Json file but wanted to still explain just in case.
I don't think this data structure will do you any favors but here is a super simple list comprehension to get it done:
host_title = 'src_host'
host_services_list = ['SSH', 'Telnet', 'STMP']
mylist = ['list item 1', 'list item 2']
hosts = [{host_title: [item, host_services_list]}
for item in mylist]
import json
print(json.dumps(hosts, indent=2))
Output:
[
{
"src_host": [
"list item 1",
[
"SSH",
"Telnet",
"STMP"
]
]
},
{
"src_host": [
"list item 2",
[
"SSH",
"Telnet",
"STMP"
]
]
}
]
The key here is starting with mylist
and building out the data from there, this may not work depending on the structure of the rest of your data though.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments