1

以下の JSON を考えると、特定の「id」の「名前」の階層リストを作成する最良の方法は何でしょうか? 階層には、任意の数のセクションが存在する可能性があります。

たとえば、ID「156」を指定すると、「ストレージ デバイスの追加、ガイド付き構成、構成」が返されます。

の使用を検討してきましたがiteritems()、助けがあればできます。

 {
    "result": true,
    "sections": [
        {
            "depth": 0,
            "display_order": 1,
            "id": 154,
            "name": "Configuration",
            "parent_id": null,
            "suite_id": 5
        },
        {
            "depth": 1,
            "display_order": 2,
            "id": 155,
            "name": "Guided Configuration",
            "parent_id": 154,
            "suite_id": 5
        },
        {
            "depth": 2,
            "display_order": 3,
            "id": 156,
            "name": "Add Storage Devices",
            "parent_id": 155,
            "suite_id": 5
        },
        {
            "depth": 0,
            "display_order": 4,
            "id": 160,
            "name": "NEW",
            "parent_id": null,
            "suite_id": 5
        },
        {
            "depth": 1,
            "display_order": 5,
            "id": 161,
            "name": "NEWS",
            "parent_id": 160,
            "suite_id": 5
        }
    ]
}
4

5 に答える 5

0

おそらく最も簡単な方法は、ID を名前にマッピングする辞書を作成することです。例えば:

name_by_id = {}
data = json.loads(the_json_string)
for section in data['sections']:
    name_by_id[section['id']] = section['name']

またはdict内包表記を使用します:

name_by_id = {section['id']: section['name'] for section in data['sections']}

次に、特定の要素を取得できます。

>>> name_by_id[156]
... 'Add Storage Devices'

またはすべての ID を取得します。

>>> name_by_id.keys()
... [160, 161, 154, 155, 156]
于 2013-07-22T09:56:46.267 に答える
0

次のようなものが欲しいと思います:

def get_name_for_id(id_num, sections):
    cur_depth = -1
    texts = []
    for elem in sections:
        if elem['depth'] < cur_depth:
            del texts[:]
        elif elem['depth'] == cur_depth:
            texts.pop()
        texts.append(elem['name'])
        cur_depth = elem['depth']
        if elem['id'] == id_num:
            return ', '.join(reversed(texts))

データを使用すると、次が返されます。

In [11]: get_name_for_id(156, data['sections'])
Out[11]: 'Add Storage Devices, Guided Configuration, Configuration'

また、 に基づく階層も考慮されるdepthため、データ内でid156depth = 0が結果を参照している場合、次のようになります。

In [16]: get_name_for_id(156, data['sections'])
Out[16]: 'Add Storage Devices'

ID 156 の深度が 1 の場合、返される値は次のとおりです。

In [22]: get_name_for_id(156, data['sections'])
Out[22]: 'Add Storage Devices, Configuration'

基本的に、ツリーを考慮します。

深さ 156 = 0 深さ 156 = 1 深さ 156 = 2

 154  156          154                 154
  |                 |                   |
  |                / \                 155
 155             155 156                |
                                       156

そして、156 からツリーのルートまでのパスにある名前の連結を返します。

于 2013-07-22T09:58:20.167 に答える