1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Python] 辞書型とかのネスト先のデータを取得する方法

Last updated at Posted at 2022-05-12

pythonでネストしたJSONデータにアクセスしたいことが結構あります。
jqを使うのを迷いつつ、でもifで繋げるのが面倒なので、簡易的にデータを抜く関数を作ってみました。
laravelで言うところのdata_get()みたいなやつです。
対応はdict() or list()です。

構造

・ lib/
   |-- __init__.py
   |-- function_utils.py
  test.py
test.py
from lib import FunctionUtils

def test():

    # ネストアイテム
    item_group = {
        "id": 1,
        "name": "hoge",
        "option": [
            {
                "sort": "ASC",
                "field": "price"
            },
            {
                "sort": "DESC",
                "field": "products"
            },
        ],
        "menu": {
            "name": "カツ丼",
            "special": False
        }
    }

    print(function_utils.nested_item_value(item_group,[]))
    print(function_utils.nested_item_value(item_group,['id']))
    print(function_utils.nested_item_value(item_group,['id','test']))
    print(function_utils.nested_item_value(item_group,['option']))
    print(function_utils.nested_item_value(item_group,['option',0]))
    print(function_utils.nested_item_value(item_group,['option',0,'field']))
    print(function_utils.nested_item_value(item_group,['option',0,'field','hoge']))
    print(function_utils.nested_item_value(item_group,['menu','special']))
    print(function_utils.nested_item_value(item_group,['menu',0,'hoge',True]))

test()
# -- 結果 ----------------------
{'id': 1, 'name': 'hoge', 'option': [{'sort': 'ASC', 'field': 'price'}, {'sort': 'DESC', 'field': 'products'}], 'menu': {'name': 'カツ丼', 'special': False}}
1
None
[{'sort': 'ASC', 'field': 'price'}, {'sort': 'DESC', 'field': 'products'}]
{'sort': 'ASC', 'field': 'price'}
price
None
False
None
lib/__init__.py
from lib.function_utils import FunctionUtils
lib/function_utils.py

class FunctionUtils:

 # ネストデータにアクセスする関数
 def nested_item_value(self,parrent_object,nest_list):
        """ return nested data """

        if not nest_list: return parrent_object

        result = ""
        for nest_key in nest_list:
            object_type = type(parrent_object)
            if object_type is not dict and object_type is not list:
                result = None
                break
            elif object_type is list:
                if type(nest_key) is not int:
                    result = None
                    break
                result = parrent_object[nest_key] if nest_key < len(parrent_object) else None
            else:
                result = parrent_object.get(nest_key,None)
            
            if result is None: break
            
            parrent_object = result
        
        return result

簡単に説明すると、
nested_item_value(parrent_object,nest_list)の第1引数に対象データを、第2引数ではネスト順でkeyを[]指定します。
・第2引数が空配列の場合、第1引数の対象データを返します。
・ネスト先にデータが存在しないときは総じてNoneを返します
もっといい書き方があると思いますが、それはまた後日追記できればと思います。
もしあれば教えて下さい。m(_ _)m

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?