简体   繁体   English

在json对象中搜索key

[英]Search for key in json object

I'm trying to make an area class that sums up all instances of the key 'area' in a json string.我正在尝试创建一个区域类,它总结了 json 字符串中键“区域”的所有实例。

For example e = Area('[1, 2, 3, {"area": 123, "weight": 1000}]') should return e=123 and this Area('["Hello", "World", {"area": 999}, {"area": 1}]') should return 1000.例如e = Area('[1, 2, 3, {"area": 123, "weight": 1000}]')应该返回e=123并且这个Area('["Hello", "World", {"area": 999}, {"area": 1}]')应该返回 1000。

At the moment I'm just getting 0 returned everytime and I think this may be because I'm initializing sum too early or because my indexing into the string may be off.目前,我每次都只返回 0,我认为这可能是因为我过早地初始化sum或者因为我对字符串的索引可能已关闭。

import json
class Area:

    def __init__(self, txt):
        self.txt=txt

    def __str__(self):
        sum=0
            for a in self.txt:
                if a == 'area':
                    sum+=int(self.txt[a]})
        return str(sum)

using json.loads is fine but you need to make sure you have a dict which you can do with isinstance , you can use the builtin sum function to do the summing for you.使用json.loads很好,但你需要确保你有一个可以用isinstance做的字典,你可以使用内置的sum函数为你做求和。

import json
class Area:
    def __init__(self, txt):
        self.txt = txt
    def __str__(self):
        return str(sum(d.get("area", 0) for d in json.loads(self.txt) 
                  if isinstance(d, dict)))

Output:输出:

In [8]: e = Area('[1, 2, 3, {"area": 123, "weight": 1000}]')

In [9]: print e
123
In [10]: e = Area('["Hello", "World", {"area": 999}, {"area": 1}]') 

In [11]: print e
1000

In your own code you are iterating over the characters in the string as you never call loads so if a == 'area': would never be True as you are comparing "area" to each individual char, as is your code would also error as self.txt[a]} is not valid syntax.在您自己的代码中,您正在迭代字符串中的字符,因为您从不调用loads因此if a == 'area':永远不会为 True,因为您将“区域”与每个单独的字符进行比较,因为您的代码也会出错因为self.txt[a]}不是有效的语法。

This works.这有效。

Then you should test each element of the list to see if it contains an item area , you should bear in mind that not all items in the list will support the in operator, so wrap it in an exception block.然后你应该测试列表的每个元素,看看它是否包含一个 item area ,你应该记住并不是列表中的所有 item 都支持in操作符,所以将它包装在一个异常块中。

Lastly it does seem odd that you are doing all this in the __str__ method.最后,您在__str__方法中执行所有这些操作似乎很奇怪。 It might be better to have a method that returns有一个返回的方法可能会更好

import json

class Area:
def __init__(self, txt):
    self.txt = json.loads(txt)

def __str__(self):
    sum = 0
    for a in self.txt:
        try:
            if 'area' in a:
                sum += int(a['area'])
        except TypeError:
            pass
    return str(sum)


print Area('[1, 2, 3, {"area": 123, "weight": 1000}]')
print Area('["Hello", "World", {"area": 999}, {"area": 1}]')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM