如何遍历多个json字典以检查相同类型的键的值?

时间:2019-04-21 20:48:57

标签: python json kivy

我希望能够在多个json词典中获取“ delta”的值。我正在使用kivy的JsonStore进行任何更改。当我按下启动check_streak函数的按钮时,出现NameError:未定义名称'delta'。这是代码:

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")

这是另一个文件中的json字典:

{"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”的值。我该怎么办?

3 个答案:

答案 0 :(得分:1)

那么变量delta不存在,因此出现错误。

想必您要for item in self.store.find("delta"):(以增量作为字符串)?

答案 1 :(得分:0)

我想您可以尝试类似的操作,其中ddself.store

In [10]: my_deltas = []

In [11]: for key in dd:
    ...:     my_deltas.append(dd[key].get('delta'))
    ...:

In [12]: my_deltas
Out[12]: [1555714261.0438898, 1555879741.894656]

答案 2 :(得分:0)

可以使用项目生成器解决此问题,以获取'delta'的值。这是代码:

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")