接口参数差异对比小功能

背景
在对接第三方系统的时候,对比参数显得是一个很繁琐的事情

  • 参数少返了
  • 参数多返了
  • 参数的核对(对应中文名称)

实现

  • python flask 框架
  • 参数的中文对照名称
  • 参数多返了哪些
  • 参数少返了哪些

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JSON Processortitle>
head>
<body>
<a href="{{ url_for('index') }}" class="bold-link"><h1>返回首页h1>a>
<h1>JSON Processorh1>
<textarea id="mapping_dict" rows="20" cols="50" placeholder="第三方接口参数标准数据(字典形式,例如:{'name':'姓名'},只一级)">textarea><br>
<textarea id="json_input" rows="20" cols="50" placeholder="实际接口参数数据(字典形式,例如:{'name':'测试'}),可多级">textarea><br>
<button onclick="processJSON()">Process JSONbutton>

<h2>Resulth2>
<pre id="result">pre>

<script>
    function isValidJSON(str) {
        try {
            JSON.parse(str);
            return true;
        } catch (e) {
            return false;
        }
    }

    async function processJSON() {
        const mappingDict = document.getElementById('mapping_dict').value;
        const jsonInput = document.getElementById('json_input').value;

        if (!isValidJSON(mappingDict)) {
            document.getElementById('result').textContent = "Error: '第三方接口参数标准数据' is not valid JSON";
            return;
        }

        if (!isValidJSON(jsonInput)) {
            document.getElementById('result').textContent = "Error: '实际接口参数数据' is not valid JSON";
            return;
        }

        try {
            const response = await fetch('{{ url_for("chayiduibi") }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    mapping_dict: JSON.parse(mappingDict),
                    json_input: JSON.parse(jsonInput)
                })
            });

            if (!response.ok) {
                throw new Error('Network response was not ok');
            }

            const result = await response.json();
            document.getElementById('result').textContent = JSON.stringify(result, null, 4);
        } catch (error) {
            document.getElementById('result').textContent = `Error: ${error.message}`;
        }
    }
script>
body>
html>

@app.route('/chayiduibipage')
def chayiduibipage():
    return render_template('chayiduibi.html')


def extract_keys(data):
    """
    递归提取字典中的所有键(包括所有层级)。
    """
    keys = set()

    def _extract(d):
        if isinstance(d, dict):
            for k, v in d.items():
                keys.add(k)
                _extract(v)
        elif isinstance(d, list):
            for item in d:
                _extract(item)

    _extract(data)
    return keys


def replace_json_keys(json_input, mapping):
    """
    递归替换JSON键名。
    """
    if isinstance(json_input, dict):
        replaced = {}
        for k, v in json_input.items():
            new_key = mapping.get(k, k)
            if new_key != k:
                new_key = f"{mapping[k]}{k})"
            replaced[new_key] = replace_json_keys(v, mapping)
        return replaced
    elif isinstance(json_input, list):
        return [replace_json_keys(item, mapping) for item in json_input]
    else:
        return json_input


@app.route('/chayiduibi', methods=['POST'])
def chayiduibi():
    data = request.json
    if not data or 'mapping_dict' not in data or 'json_input' not in data:
        return jsonify({"error": "Invalid input"}), 400
    mapping_dict = data['mapping_dict']
    json_input = data['json_input']
    # 提取所有层级的键
    json_keys = extract_keys(json_input)
    mapping_keys = set(mapping_dict.keys())

    # 计算差异
    extra_keys = list(json_keys - mapping_keys)  # JSON有但映射无
    missing_keys = list(mapping_keys - json_keys)  # 映射有但JSON无

    # 替换键名
    replaced_json = replace_json_keys(json_input, mapping_dict)

    # 构造最终结果
    final_result = {
        "请求匹配后的值": replaced_json,
        "差异值": {
            "传第三方值传多了": extra_keys,
            "传第三方值传少了": missing_keys
        }
    }
    # 输出
    return (json.dumps(final_result, ensure_ascii=False, indent=4))

接口参数差异对比小功能_第1张图片

你可能感兴趣的:(python,test,python)