簡體   English   中英

生成兩個JSON文件之間的值差異

[英]Generate differences in values between two JSON files

我有一個JSON主配置文件,其值可能會被特定帳戶的配置文件(同樣在JSON中)覆蓋。

主文件

{
    "section1Configs": {
        "setting01": true,
        "setting02": true,
        "setting03": false
    },
    section2Configs: {
        "setting01": true,
        "setting02": true,
        "setting03": false
    },
    section3Configs: {
        "setting01": true,
        "setting02": true,
        "setting03": false
    },
    section4Configs: {
        "setting01": true,
        "setting02": true,
        "setting03": false
    }
}

配置文件

{
    "section1Configs": {
        "setting01": true,
        "setting02": true,
        "setting03": true
    },
    section2Configs: {
        "setting01": false,
        "setting02": true,
        "setting03": false
    },
    section3Configs: {
        "setting01": true,
        "setting02": false,
        "setting03": false
    },
    section4Configs: {
        "setting01": true,
        "setting02": true,
        "setting03": false
    }
}

請注意,它們是相同的,只是某些值( section01Config.setting03section02Config.setting01section03Config.setting02 )不同。 還要注意,兩個文件中的整個section4Configs塊都相同。

不需要相同的文件,因為應用程序會同時加載這兩個文件,並使用帳戶配置中不同的文件覆蓋主文件。

我想做的是擁有一個腳本,該腳本可循環訪問此類帳戶文件的目錄,並刪除每個文件中與主文件相同的鍵和值的條目。 從這個例子中,我最終得到一個像這樣的文件:

{
    section1Configs: {
        setting03: true
    },
    section2Configs: {
        setting01: false
    },
    section3Configs: {
        setting02: false
    }
}

假設這兩個文件格式正確,並且結構與示例相同(尤其是深度),則解決方案很簡單:

在PHP中:

$master = json_decode($master, true);
$config = json_decode($config, true);

$result = [];

foreach ($master as $ksec => $vsec) {
    $secTmp = [];
    foreach ($vsec as $kset => $vset) {
        if ($master[$ksec][$kset] !== $config[$ksec][$kset])
            $secTmp[$kset] = $config[$ksec][$kset];
    }
    if ($secTmp)
        $result[$ksec] = $secTmp;
}
echo json_encode($result);

我知道OP並沒有請求Python,但是如果有人遇到類似的問題並且不想被運行(甚至安裝)PHP和Apache所困擾,這是一個朴素的Python實現。

import json


with open('json1.json') as data_file:
    master = json.load(data_file)

with open('json2.json') as data_file:
    config = json.load(data_file)

result = {}

for section in master:
    for attribute, value in master[section].items():
        if not config[section][attribute] == value:
            result.update({section: {}})
            result[section].update({attribute: value})

with open('result.json', 'w') as f:
    json.dump(result, f, indent=4)

注意:該解決方案不保留attribute s和section的順序。 它還需要(並生成) 格式良好的JSON ,如下所示:

{
    "section3Configs": {
        "setting02": true
    },
    "section1Configs": {
        "setting03": false
    },
    "section2Configs": {
        "setting01": true
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM