The Fastest method to find element in JSON (Python)

This question already has an answer here:

  • Parsing values from a JSON file? 7 answers

  • Here's an easy way to do it:

    def function(json_object, name):
        for dict in json_object:
            if dict['name'] == name:
                return dict['price']
    

    If you are sure that there are no duplicate names, an even more effective (and pythonic way to do it is to use list comprehensions:

    def function(json_object, name):
            return [obj for obj in json_object if obj['name']==name][0]['price']
    

    from json import loads
    
    json = """[
     {
      "name":"Apple",
      "price":2,
      "have":0,
      "max":36
     },
     {
      "name":"Pineapple",
      "price":5,
      "have":6,
      "max":17
     }
    ]"""
    
    parsedJson = loads (json)
    
    def jsonname (name):
        for entry in parsedJson:
            if name == entry ['name']:
                return entry ['price']
    
    链接地址: http://www.djcxy.com/p/38042.html

    上一篇: 在Python中从JSON数据创建列表和词典

    下一篇: 在JSON中查找元素的最快速方法(Python)