問題描述
我希望能夠在多個 json 字典中獲取delta"的值.如果有任何改變,我正在使用來自 kivy 的 JsonStore.當(dāng)我按下啟動 check_streak 函數(shù)的按鈕時,我得到 NameError: name 'delta' is not defined.代碼如下:
I want to be able to get the value of "delta" in multiple json dictionaries. I'm using JsonStore from kivy if that changes anything. When I press the button that starts the check_streak function I get NameError: name 'delta' is not defined. Here is the code:
class MainApp(App):
def build(self): # build() returns an instance
self.store = JsonStore("streak.json") # file that stores the streaks:
return presentation
def check_streak(self, instance):
for item in self.store.find(delta):
if delta > time.time():
print("early")
if delta == time.time():
print("on time")
if delta < time.time():
print("late")
這是一個單獨(dú)文件中的 json 字典:
Here is the json dictionary in a seperate file:
{"first": {"action": "first", "action_num": "1", "seconds": 60, "score": 0, "delta": 1555714261.0438898}, "second": {"action": "second", "action_num": "2", "seconds": 120, "score": 0, "delta": 1555879741.894656}}
我希望能夠從文件中的每個對象中獲取delta"的值.我該怎么做?
I want to be able to get the value of "delta" from every object put inside the file. How would I do this?
推薦答案
這個問題可以用item generator來得到'delta'
的值.代碼如下:
This question can be solved with an item generator to get the value of 'delta'
. Here is the code:
class MainApp(App):
def build(self): # build() returns an instance
self.store = JsonStore("streak.json") # file that stores the streaks:
return presentation
# Gets the value of delta (code I may never understand lol)
def item_generator(self, json_input, lookup_key):
if isinstance(json_input, dict):
for k, v in json_input.items():
if k == lookup_key:
yield v
else:
yield from self.item_generator(v, lookup_key)
elif isinstance(json_input, list):
for item in json_input:
yield from self.item_generator(item, lookup_key)
def check_streak(self, instance):
with open("streak.json", "r") as read_file:
data = json.load(read_file)
values = self.item_generator(data, 'delta')
for honey in values:
if honey > time.time():
print("early")
if honey == time.time():
print("on time")
if honey < time.time():
print("late")
這篇關(guān)于如何遍歷多個 json 字典來檢查相同類型鍵的值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!