0
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?

JSON構造からキーの一覧を生成する

Posted at

仕様

ルート

ルートハッシュは

$

キー

{
  "key1": "value"
}

$.key1

サブキー

{
  "key1": "value",
  "key2": {
    "key3": "value"
  }
}

$.key1
$.key2.key3

配列

{
  "key1": "value",
  "key2": {
    "key3": "value"
  },
  "key4": [
      "value",
      "value"
  ],
  "key5": [
    {
      "key6": "value"
    },
    {
      "key6": "value"
    }
  ]
}

$.key1
$.key2.key3
$.key4[]
$.key5[].key6

スクリプト

import json
import sys

def list_keys(json_obj, prefix='$'):
    keys = []
    
    if isinstance(json_obj, dict):
        for key, value in json_obj.items():
            new_prefix = f"{prefix}.{key}"
            keys.extend(list_keys(value, new_prefix))
    elif isinstance(json_obj, list):
        new_prefix = f"{prefix}[]"
        if json_obj:
            for item in json_obj:
                keys.extend(list_keys(item, new_prefix))
        else:
            keys.append(new_prefix)
    else:
        keys.append(prefix)
    
    return keys

# 標準入力からJSONデータを読み込む
input_data = sys.stdin.read()

try:
    json_obj = json.loads(input_data)
    keys_list = list_keys(json_obj)

    for key in keys_list:
        print(key)
except json.JSONDecodeError:
    print("入力が有効なJSONではありません。")
0
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
0
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?