json strip multiple lists

This question already has an answer here:

  • Parsing values from a JSON file? 7 answers

  • I think this is what @Jean-François Fabre tried to indicate:

    import json
    
    response = """
        {
          "age":[
            {"#":"1","age":10},
            {"#":"2","age":12},
            {"#":"3","age":16},
            {"#":"4","age":3}
          ],
          "age2":[
            {"#":"1","age":10},
            {"#":"2","age":12},
            {"#":"3","age":16},
            {"#":"4","age":3}
          ],
          "days_month":31,
          "year":2017
        }
    """
    
    j = json.loads(response)
    # note that the [2] means the third element in the "age2" list-of-dicts
    print(j['age2'][2]['#'])  # -> 3
    print(j['age2'][2]['age'])  # -> 16
    

    json.loads() converts a string in JSON format into a Python object. In particular it converts JSON objects into Python dictionaries and JSON lists into Python list objects. This means you can access the contents of the result stored in the variable j in this case, just like you would if it was a native mixture of one or more of those types of Python datatypes (and would look very similar to what is shown in the response).


    As the search criterion you are looking for is not contained in the indices of the respective datastructures, I would do it using a list comprehension. For your example, this would be

    [person['age'] for person in j['age2'] if person['#'] == u'3'][0]
    

    This iterates through all the items in the list under 'age2', and puts all the items where the number is '3' into a list. The [0] selects the first entry of the list.

    However, this is very inefficient. If you have large datasets, you might want to have a look at pandas:

    df = pandas.DataFrame(j['age2'])
    df[df['#'] == '3']['age']
    

    which is much more performant as long as your data can be represented by a sort of series or table.

    链接地址: http://www.djcxy.com/p/38056.html

    上一篇: 正则表达式获取URL链接

    下一篇: json去掉多个列表