The thing I want to do is, search the "name" data of line, find it, and extract every data on the same line.
For example , [{"name": "Rusted Abyss Scarab", "exaltedValue": 0, "chaosValue": 0.5, "currType": "Chaos Orb"}] considering this line I want to search for "Abyss" in my function and when I get this in my search, I want to extract name, exaltedValue, chaosValue and currType.
class SearchScarab(list):
def search(self,name):
matching_items = []
for item in self:
if name in item.name: #Matching name column here and it is success.
matching_items.append(item) #Appending the item name to the matching_item
os.chdir(r"C:\Users\emosc\PycharmProjects\GithubPushs\psychescape_price_fetcher\psychescape_price_fetcher\values")
with open("scarab.txt", "r") as file:
data = file.read()
index = matching_items.index(item)
print(index) #Trying to get index of the item line
print(data[index]) #Print data of the index of item line, prints nothing.
break
return matching_items
When I run the full code with the search function above with
[c1.name for c1 in ScarabValues.exportfunction.search("Abyss")] #c = ScarabValues, c.Scarab_Values
['Rusted Abyss Scarab']
the first line, it outputs the second line. I want to full print the values like ["Rusted Abyss Scarab"], ["0"], ["0.5"], ["Chaos Orb"] (They are all from the same line). How?
CodePudding user response:
You could parse the data into dictionary and get the data using it.
import json
item = """[{"name": "Winged Abyss Scarab", "exaltedValue": 0, "chaosValue": 90.0, "currType": "Chaos Orb"}]"""
# Convert it to dict object, indexing is used since it is a list with a single element
parsed = json.loads(item)[0]
# Now you can access to the data with keys
name = parsed['name'] # 'Winged Abyss Scarab'
exalted_value = parsed['exaltedValue'] # 0
chaos_value = parsed['chaosValue'] # 90.0
curr_type = parsed['currType'] # 'Chaos Orb'
It is doable without json module of course, but that would unnecessarilly overcomplicate things.
CodePudding user response:
You should first try converting to a dictionary object and then run the lookup
import json
data = []
def find_name(value):
matches = []
for item in data:
if value in item['name']:
matches = [item]
for match in matches:
for val in match.values():
print(val, end=", ")
print()
with open('<path to the file>', 'r') as f:
for line in f.readlines():
data = json.loads(line.strip())
find_name("Abyss")
>>> Winged Abyss Scarab, 0, 90.0, Chaos Orb
... Gilded Abyss Scarab, 0, 30.0, Chaos Orb
... Polished Abyss Scarab, 0, 3.0, Chaos Orb
... Rusted Abyss Scarab, 0, 0.5, Chaos Orb
That will basically check the name in all the elements and print all the values in the dictionary. You can change the output format if you want to.
