你知唔知我系靓仔

获取JSON数据的字段及其值的类型

使用Python的json模块来解析原始的JSON文件,并递归地遍历JSON结构以提取所有字段,然后将这些字段及其类型保存到一个新的JSON文件中

import json
from collections import OrderedDict

def extract_structure(data, parent_key=''):
    structure = OrderedDict()

    if isinstance(data, dict):
        for key, value in data.items():
            new_key = f"{parent_key}.{key}" if parent_key else key
            structure.update(extract_structure(value, new_key))
    elif isinstance(data, list):
        if data:
            structure.update(extract_structure(data[0], parent_key))
    else:
        if isinstance(data, str):
            structure[parent_key] = "string"
        elif isinstance(data, int):
            structure[parent_key] = "integer"
        elif isinstance(data, float):
            structure[parent_key] = "float"
        elif isinstance(data, bool):
            structure[parent_key] = "boolean"
        else:
            structure[parent_key] = "null"

    return structure

def structure_to_json(structure):
    json_structure = OrderedDict()

    for key, value in structure.items():
        keys = key.split('.')
        current = json_structure

        for k in keys[:-1]:
            if k not in current:
                current[k] = OrderedDict()
            current = current[k]

        current[keys[-1]] = value if value in ["string", "integer", "float", "boolean"] else None

    return json_structure

def main():
    # 读取原始JSON文件
    with open('1.json', 'r') as file:
        data = json.load(file)

    # 提取结构
    structure = extract_structure(data)

    # 转换为期望的JSON格式
    json_structure = structure_to_json(structure)

    # 保存到新的JSON文件
    with open('complete_structure.json', 'w') as file:
        json.dump(json_structure, file, indent=4)

if __name__ == "__main__":
    main()

代码说明:

  1. extract_structure函数:递归地遍历JSON数据,提取所有字段及其类型,并将它们存储在一个有序字典中。
  2. structure_to_json函数:将提取的结构转换为期望的JSON格式,其中每个字段的值被替换为相应的类型(如"string""integer"等)。
  3. main函数:读取原始JSON文件,调用上述两个函数生成最终的JSON结构,并将其保存到complete_structure.json文件中。

注意事项:

  • 代码假设输入的JSON文件是有效的,并且没有嵌套的列表或字典中包含不同类型的值。
  • 代码使用OrderedDict来保持字段的顺序,以确保生成的JSON文件的结构与原始数据一致。

示例输入(1.json):

{
    "game_id": "12345",
    "lifetime": {
        "property1": "value1",
        "property2": 123
    },
    "player_id": "player1",
    "segments": [
        {
            "property1": "segment1",
            "property2": 456
        }
    ]
}

示例输出(complete_structure.json):

{
    "game_id": "string",
    "lifetime": {
        "property1": "string",
        "property2": "integer"
    },
    "player_id": "string",
    "segments": [
        {
            "property1": "string",
            "property2": "integer"
        }
    ]
}