简体   繁体   中英

How to merge two JSON files into one

I have two json files named: users.json and users_custom.json which I created from mysql database using php. users.json file looks like:

[{
    "user_id" : "1",
    "Name" : "Mr. A",
    "phone" : "12345"
},
{
    "user_id" : "2",
    "Name" : "Mr. B",
    "phone" : "23456"
}]

and users_custom.json file looks like:

[{
    "user_id" : "1",
    "Name" : "Mr. A Modified",
    "email" : "someone@gmail.com"
},
{
    "user_id" : "2",
    "Name" : "Mr. B",
    "address" : "some address"
}]

so, in users_custom.json file I have modified some fields and also added some new fields. Now, I want to merge users_custom.json over users.json file into users_final.json file. At the end users_final file should looks like this:

[{
    "user_id" : "1",
    "Name" : "Mr. A Modified",
    "phone" : "12345"
    "email" : "someone@gmail.com"
},
{
    "user_id" : "2",
    "Name" : "Mr. B",
    "phone" : "23456"
    "address" : "some address"
}]

At the end I will import the users_final.json file to MongoDB database. Any idea or example code will be greatly appreciated. Thanks in advance.

This should be fairly straightforward, get contents of both files, decode them both, loop them accordingly, if the user id's match, merge them, after that process is complete, encode the resultant, then write the file. Example:

// $contents_of_users = file_get_contents('users.json');
$contents_of_users = '[{ "user_id" : "1", "Name" : "Mr. A", "phone" : "12345"},{ "user_id" : "2", "Name" : "Mr. B", "phone" : "23456"}]';
// $contents_of_users_custom = file_get_contents('users_custom.json');
$contents_of_users_custom = '[{ "user_id" : "1", "Name" : "Mr. A Modified", "email" : "someone@gmail.com"},{ "user_id" : "2", "Name" : "Mr. B", "address" : "some address"}]';

$data_user = json_decode($contents_of_users, true);
$data_user_custom = json_decode($contents_of_users_custom, true);
$final = $data_user;
foreach($final as $key => &$user) {
    foreach($data_user_custom as $user_custom) {
        if($user['user_id'] == $user_custom['user_id']) {
            $user = array_merge($user, $user_custom);
        }
    }
}

$final = json_encode($final, JSON_PRETTY_PRINT);
echo '<pre>';
print_r($final);

file_put_contents('users_final.json', $final);

Sample Output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM