'Python Parsing through complex list that is just really 1 string of characters
I parsed a extremely LONG dictionary for the the fields 'zones' to a variable called scanner_data. In the next paragraph I'm showing the type of scanner_data. The next line after that is the contents of scanner_data.
Variable: scanner_data. The type is : <class 'list'>
[{'id': '3', 'name': 'rcomultitfw', ALL THE REST OF THE STRING IS WORTHLESS TO ME. IT WILL GO ON FOR another 700 letters!
I want to parse the name field for the results of rcomultitfw. I've tried .split(). I've tried converting the list thats really a string to a dictionary so I could parse it again, however it crashes or my python skills are not up to par. If you print(scanner_data[1]) it states its out of range so its the only result of this list.
Just for your information this data was taken from tenables with PyTenables.sc, not sure if that will help or not. My end goal is to parse scan zone data from information from individual tenable scanners.
Please Please help. I was enjoying Python programming up until this point, now I'm pulling out my hair and having headaches. Thanks!
Solution 1:[1]
If you can post the code and the console details it would be alot better. However, from what's shown, the data returned is of type list and it contains only one index, so functions like ".split()" won't work since they are only meant for variable of type string. What you might be missing is to first get the dictionary wrapped inside the array then try to access this dictionary using the keys. Here is an example:
scanner_data = [{'id': '3', 'name': 'rcomultitfw', 'extras':'ALL THE REST OF THE STRING I'}]
print(scanner_data[0]['name'])
However, since your question is not so clear I'll try to give an answer for other two possible scenarios:
Scenario A, having a dictionary that's wrapped in a string inside the array:
import ast
scanner_data = ["{'id': '3', 'name': 'rcomultitfw', 'extras':'ALL THE REST OF THE STRING I'}"]
dict_data = scanner_data[0]
parsed_dict = ast.literal_eval(dict_data)
print(parsed_dict['name'])
Scenario B, having a faulty dictionary that will ruin the parser:
import ast
scanner_data = ["{'id': '3', 'name': 'rcomultitfw', 'ALL THE REST OF THE STRING I'}"]
dict_data = scanner_data[0]
adjusted_string = dict_data.split(',')
adjusted_string = adjusted_string[0] + "," + adjusted_string[1] + '}'
parsed_dict = ast.literal_eval(adjusted_string)
print(parsed_dict['name'])
This is not the best way to adjust faulty dictionaries but this can work for your own use case and you can but this logic in a loop if you have multiple dictionaries in the scanner_data list
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
