How to merge JSON files?












-2















How can I use ordered dictionary in python older versions?










share|improve this question





























    -2















    How can I use ordered dictionary in python older versions?










    share|improve this question



























      -2












      -2








      -2








      How can I use ordered dictionary in python older versions?










      share|improve this question
















      How can I use ordered dictionary in python older versions?







      python json python-3.x






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 20 '18 at 2:11







      Abhishek Allamsetty

















      asked Nov 22 '18 at 10:57









      Abhishek AllamsettyAbhishek Allamsetty

      155




      155
























          3 Answers
          3






          active

          oldest

          votes


















          1














          from collections import OrderedDict
          from functools import partial
          import json
          import sys

          if sys.version_info < (3,6): # Pre Python 3.6?
          ordered_json_load = partial(json.load, object_pairs_hook=OrderedDict)
          else:
          ordered_json_load = json.load

          with open('file1.json') as finput1, open('file2.json') as finput2:

          # Merge data from files.
          merged = ordered_json_load(finput1)
          merged['body'].update(ordered_json_load(finput2)['body'].items())

          # Write the merged data to an output file.
          with open('output.json', 'w') as foutput:
          json.dump(merged, foutput, indent=4)


          Contents of output file produced:



          {
          "head-param": "foo",
          "head-param1": "bar",
          "head-sub-param": {
          "head-sub-param1": "foo",
          "head-sub-param2": "bar"
          },
          "body": {
          "name1": {
          "value": "foo",
          "option": "bar",
          "bar": "bar",
          "foo": "foo",
          "baz": "baz"
          },
          "name22": {
          "value1": "foo1",
          "option1": "bar1",
          "bar1": "bar1",
          "foo1": "foo1",
          "baz1": "baz1"
          }
          }
          }





          share|improve this answer


























          • Thanks for the help it works, but I have some issues with that where lines are not properly aligned and also the output is not in order of the source JSON file. Please suggest me the way so that I can eliminate even that issue.

            – Abhishek Allamsetty
            Nov 22 '18 at 14:22











          • Abhishek: OK, modified to automatically preserve the order when necessary (depends on exact version of Python being used). Also prettied-up the lines dumped to the output file (assuming that's what you meant by "properly aligned").

            – martineau
            Nov 22 '18 at 18:06






          • 1





            Thank you so much it really helps me a lot. It works as per my expectation. Thank you so much.

            – Abhishek Allamsetty
            Nov 22 '18 at 23:09



















          1














          I would use jsonmerge to merge your json files. It handles the merging of JSON files quite well.



          You can install this library with pip install jsonmerge.



          Demo:



          from json import loads
          from json import dump

          from jsonmerge import merge

          # Store your json files here
          # If all of them exist in directory, you can use os.listdir() instead
          json_files = ['file1.json', 'file2.json']

          with open('merged.json', 'w') as json_out:

          # Store updated results in this dict
          data = {}

          for file in json_files:
          with open(file, 'rb') as json_file:
          json_data = loads(json_file.read())

          # Update result dict with merged data
          data.update(merge(data, json_data))

          dump(data, json_out, indent=4)


          Which gives the following merged.json:



          {
          "head-param": "foo",
          "head-param1": "bar",
          "head-sub-param": {
          "head-sub-param1": "foo",
          "head-sub-param2": "bar"
          },
          "body": {
          "name1": {
          "value": "foo",
          "option": "bar",
          "bar": "bar",
          "foo": "foo",
          "baz": "baz"
          },
          "name22": {
          "value1": "foo1",
          "option1": "bar1",
          "bar1": "bar1",
          "foo1": "foo1",
          "baz1": "baz1"
          }
          }
          }





          share|improve this answer

































            1














            You could write a little recursive function:



            def update_nested_dict(dict_1, dict_2):
            """Mutate dict_1 by updating it with all values present in dict_2."""
            for key, value in dict_2.items():
            if key not in dict_1:
            # Just add the value to dict_1
            dict_1[key] = value
            continue

            if isinstance(value, dict):
            # If this is a dict then let's recurse...
            update_nested_dict(dict_1[key], value)


            Calling update_nested_dict(json1, json2) mutates json1 to:



            {'head-param': 'foo',
            'head-param1': 'bar',
            'head-sub-param': {'head-sub-param1': 'foo', 'head-sub-param2': 'bar'},
            'body': {'name1': {'value': 'foo',
            'option': 'bar',
            'bar': 'bar',
            'foo': 'foo',
            'baz': 'baz'},
            'name22': {'value1': 'foo1',
            'option1': 'bar1',
            'bar1': 'bar1',
            'foo1': 'foo1',
            'baz1': 'baz1'}}}





            share|improve this answer
























            • You've basically implemented in pure Python what the built-in dict.update() method would do much more quickly.

              – martineau
              Nov 22 '18 at 18:12











            • I don't think that's quite true, unless dict.update has a recursive option?

              – Bernard Stockermans
              Nov 23 '18 at 16:36






            • 1





              Bernard: No, dict.update() doesn't have an option like that—but it doesn't need one. Here's an example with some proof (in addition, of course, to my own answer to this question).

              – martineau
              Nov 23 '18 at 19:36













            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53429414%2fhow-to-merge-json-files%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            3 Answers
            3






            active

            oldest

            votes








            3 Answers
            3






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            from collections import OrderedDict
            from functools import partial
            import json
            import sys

            if sys.version_info < (3,6): # Pre Python 3.6?
            ordered_json_load = partial(json.load, object_pairs_hook=OrderedDict)
            else:
            ordered_json_load = json.load

            with open('file1.json') as finput1, open('file2.json') as finput2:

            # Merge data from files.
            merged = ordered_json_load(finput1)
            merged['body'].update(ordered_json_load(finput2)['body'].items())

            # Write the merged data to an output file.
            with open('output.json', 'w') as foutput:
            json.dump(merged, foutput, indent=4)


            Contents of output file produced:



            {
            "head-param": "foo",
            "head-param1": "bar",
            "head-sub-param": {
            "head-sub-param1": "foo",
            "head-sub-param2": "bar"
            },
            "body": {
            "name1": {
            "value": "foo",
            "option": "bar",
            "bar": "bar",
            "foo": "foo",
            "baz": "baz"
            },
            "name22": {
            "value1": "foo1",
            "option1": "bar1",
            "bar1": "bar1",
            "foo1": "foo1",
            "baz1": "baz1"
            }
            }
            }





            share|improve this answer


























            • Thanks for the help it works, but I have some issues with that where lines are not properly aligned and also the output is not in order of the source JSON file. Please suggest me the way so that I can eliminate even that issue.

              – Abhishek Allamsetty
              Nov 22 '18 at 14:22











            • Abhishek: OK, modified to automatically preserve the order when necessary (depends on exact version of Python being used). Also prettied-up the lines dumped to the output file (assuming that's what you meant by "properly aligned").

              – martineau
              Nov 22 '18 at 18:06






            • 1





              Thank you so much it really helps me a lot. It works as per my expectation. Thank you so much.

              – Abhishek Allamsetty
              Nov 22 '18 at 23:09
















            1














            from collections import OrderedDict
            from functools import partial
            import json
            import sys

            if sys.version_info < (3,6): # Pre Python 3.6?
            ordered_json_load = partial(json.load, object_pairs_hook=OrderedDict)
            else:
            ordered_json_load = json.load

            with open('file1.json') as finput1, open('file2.json') as finput2:

            # Merge data from files.
            merged = ordered_json_load(finput1)
            merged['body'].update(ordered_json_load(finput2)['body'].items())

            # Write the merged data to an output file.
            with open('output.json', 'w') as foutput:
            json.dump(merged, foutput, indent=4)


            Contents of output file produced:



            {
            "head-param": "foo",
            "head-param1": "bar",
            "head-sub-param": {
            "head-sub-param1": "foo",
            "head-sub-param2": "bar"
            },
            "body": {
            "name1": {
            "value": "foo",
            "option": "bar",
            "bar": "bar",
            "foo": "foo",
            "baz": "baz"
            },
            "name22": {
            "value1": "foo1",
            "option1": "bar1",
            "bar1": "bar1",
            "foo1": "foo1",
            "baz1": "baz1"
            }
            }
            }





            share|improve this answer


























            • Thanks for the help it works, but I have some issues with that where lines are not properly aligned and also the output is not in order of the source JSON file. Please suggest me the way so that I can eliminate even that issue.

              – Abhishek Allamsetty
              Nov 22 '18 at 14:22











            • Abhishek: OK, modified to automatically preserve the order when necessary (depends on exact version of Python being used). Also prettied-up the lines dumped to the output file (assuming that's what you meant by "properly aligned").

              – martineau
              Nov 22 '18 at 18:06






            • 1





              Thank you so much it really helps me a lot. It works as per my expectation. Thank you so much.

              – Abhishek Allamsetty
              Nov 22 '18 at 23:09














            1












            1








            1







            from collections import OrderedDict
            from functools import partial
            import json
            import sys

            if sys.version_info < (3,6): # Pre Python 3.6?
            ordered_json_load = partial(json.load, object_pairs_hook=OrderedDict)
            else:
            ordered_json_load = json.load

            with open('file1.json') as finput1, open('file2.json') as finput2:

            # Merge data from files.
            merged = ordered_json_load(finput1)
            merged['body'].update(ordered_json_load(finput2)['body'].items())

            # Write the merged data to an output file.
            with open('output.json', 'w') as foutput:
            json.dump(merged, foutput, indent=4)


            Contents of output file produced:



            {
            "head-param": "foo",
            "head-param1": "bar",
            "head-sub-param": {
            "head-sub-param1": "foo",
            "head-sub-param2": "bar"
            },
            "body": {
            "name1": {
            "value": "foo",
            "option": "bar",
            "bar": "bar",
            "foo": "foo",
            "baz": "baz"
            },
            "name22": {
            "value1": "foo1",
            "option1": "bar1",
            "bar1": "bar1",
            "foo1": "foo1",
            "baz1": "baz1"
            }
            }
            }





            share|improve this answer















            from collections import OrderedDict
            from functools import partial
            import json
            import sys

            if sys.version_info < (3,6): # Pre Python 3.6?
            ordered_json_load = partial(json.load, object_pairs_hook=OrderedDict)
            else:
            ordered_json_load = json.load

            with open('file1.json') as finput1, open('file2.json') as finput2:

            # Merge data from files.
            merged = ordered_json_load(finput1)
            merged['body'].update(ordered_json_load(finput2)['body'].items())

            # Write the merged data to an output file.
            with open('output.json', 'w') as foutput:
            json.dump(merged, foutput, indent=4)


            Contents of output file produced:



            {
            "head-param": "foo",
            "head-param1": "bar",
            "head-sub-param": {
            "head-sub-param1": "foo",
            "head-sub-param2": "bar"
            },
            "body": {
            "name1": {
            "value": "foo",
            "option": "bar",
            "bar": "bar",
            "foo": "foo",
            "baz": "baz"
            },
            "name22": {
            "value1": "foo1",
            "option1": "bar1",
            "bar1": "bar1",
            "foo1": "foo1",
            "baz1": "baz1"
            }
            }
            }






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 22 '18 at 17:52

























            answered Nov 22 '18 at 11:45









            martineaumartineau

            68.4k1090183




            68.4k1090183













            • Thanks for the help it works, but I have some issues with that where lines are not properly aligned and also the output is not in order of the source JSON file. Please suggest me the way so that I can eliminate even that issue.

              – Abhishek Allamsetty
              Nov 22 '18 at 14:22











            • Abhishek: OK, modified to automatically preserve the order when necessary (depends on exact version of Python being used). Also prettied-up the lines dumped to the output file (assuming that's what you meant by "properly aligned").

              – martineau
              Nov 22 '18 at 18:06






            • 1





              Thank you so much it really helps me a lot. It works as per my expectation. Thank you so much.

              – Abhishek Allamsetty
              Nov 22 '18 at 23:09



















            • Thanks for the help it works, but I have some issues with that where lines are not properly aligned and also the output is not in order of the source JSON file. Please suggest me the way so that I can eliminate even that issue.

              – Abhishek Allamsetty
              Nov 22 '18 at 14:22











            • Abhishek: OK, modified to automatically preserve the order when necessary (depends on exact version of Python being used). Also prettied-up the lines dumped to the output file (assuming that's what you meant by "properly aligned").

              – martineau
              Nov 22 '18 at 18:06






            • 1





              Thank you so much it really helps me a lot. It works as per my expectation. Thank you so much.

              – Abhishek Allamsetty
              Nov 22 '18 at 23:09

















            Thanks for the help it works, but I have some issues with that where lines are not properly aligned and also the output is not in order of the source JSON file. Please suggest me the way so that I can eliminate even that issue.

            – Abhishek Allamsetty
            Nov 22 '18 at 14:22





            Thanks for the help it works, but I have some issues with that where lines are not properly aligned and also the output is not in order of the source JSON file. Please suggest me the way so that I can eliminate even that issue.

            – Abhishek Allamsetty
            Nov 22 '18 at 14:22













            Abhishek: OK, modified to automatically preserve the order when necessary (depends on exact version of Python being used). Also prettied-up the lines dumped to the output file (assuming that's what you meant by "properly aligned").

            – martineau
            Nov 22 '18 at 18:06





            Abhishek: OK, modified to automatically preserve the order when necessary (depends on exact version of Python being used). Also prettied-up the lines dumped to the output file (assuming that's what you meant by "properly aligned").

            – martineau
            Nov 22 '18 at 18:06




            1




            1





            Thank you so much it really helps me a lot. It works as per my expectation. Thank you so much.

            – Abhishek Allamsetty
            Nov 22 '18 at 23:09





            Thank you so much it really helps me a lot. It works as per my expectation. Thank you so much.

            – Abhishek Allamsetty
            Nov 22 '18 at 23:09













            1














            I would use jsonmerge to merge your json files. It handles the merging of JSON files quite well.



            You can install this library with pip install jsonmerge.



            Demo:



            from json import loads
            from json import dump

            from jsonmerge import merge

            # Store your json files here
            # If all of them exist in directory, you can use os.listdir() instead
            json_files = ['file1.json', 'file2.json']

            with open('merged.json', 'w') as json_out:

            # Store updated results in this dict
            data = {}

            for file in json_files:
            with open(file, 'rb') as json_file:
            json_data = loads(json_file.read())

            # Update result dict with merged data
            data.update(merge(data, json_data))

            dump(data, json_out, indent=4)


            Which gives the following merged.json:



            {
            "head-param": "foo",
            "head-param1": "bar",
            "head-sub-param": {
            "head-sub-param1": "foo",
            "head-sub-param2": "bar"
            },
            "body": {
            "name1": {
            "value": "foo",
            "option": "bar",
            "bar": "bar",
            "foo": "foo",
            "baz": "baz"
            },
            "name22": {
            "value1": "foo1",
            "option1": "bar1",
            "bar1": "bar1",
            "foo1": "foo1",
            "baz1": "baz1"
            }
            }
            }





            share|improve this answer






























              1














              I would use jsonmerge to merge your json files. It handles the merging of JSON files quite well.



              You can install this library with pip install jsonmerge.



              Demo:



              from json import loads
              from json import dump

              from jsonmerge import merge

              # Store your json files here
              # If all of them exist in directory, you can use os.listdir() instead
              json_files = ['file1.json', 'file2.json']

              with open('merged.json', 'w') as json_out:

              # Store updated results in this dict
              data = {}

              for file in json_files:
              with open(file, 'rb') as json_file:
              json_data = loads(json_file.read())

              # Update result dict with merged data
              data.update(merge(data, json_data))

              dump(data, json_out, indent=4)


              Which gives the following merged.json:



              {
              "head-param": "foo",
              "head-param1": "bar",
              "head-sub-param": {
              "head-sub-param1": "foo",
              "head-sub-param2": "bar"
              },
              "body": {
              "name1": {
              "value": "foo",
              "option": "bar",
              "bar": "bar",
              "foo": "foo",
              "baz": "baz"
              },
              "name22": {
              "value1": "foo1",
              "option1": "bar1",
              "bar1": "bar1",
              "foo1": "foo1",
              "baz1": "baz1"
              }
              }
              }





              share|improve this answer




























                1












                1








                1







                I would use jsonmerge to merge your json files. It handles the merging of JSON files quite well.



                You can install this library with pip install jsonmerge.



                Demo:



                from json import loads
                from json import dump

                from jsonmerge import merge

                # Store your json files here
                # If all of them exist in directory, you can use os.listdir() instead
                json_files = ['file1.json', 'file2.json']

                with open('merged.json', 'w') as json_out:

                # Store updated results in this dict
                data = {}

                for file in json_files:
                with open(file, 'rb') as json_file:
                json_data = loads(json_file.read())

                # Update result dict with merged data
                data.update(merge(data, json_data))

                dump(data, json_out, indent=4)


                Which gives the following merged.json:



                {
                "head-param": "foo",
                "head-param1": "bar",
                "head-sub-param": {
                "head-sub-param1": "foo",
                "head-sub-param2": "bar"
                },
                "body": {
                "name1": {
                "value": "foo",
                "option": "bar",
                "bar": "bar",
                "foo": "foo",
                "baz": "baz"
                },
                "name22": {
                "value1": "foo1",
                "option1": "bar1",
                "bar1": "bar1",
                "foo1": "foo1",
                "baz1": "baz1"
                }
                }
                }





                share|improve this answer















                I would use jsonmerge to merge your json files. It handles the merging of JSON files quite well.



                You can install this library with pip install jsonmerge.



                Demo:



                from json import loads
                from json import dump

                from jsonmerge import merge

                # Store your json files here
                # If all of them exist in directory, you can use os.listdir() instead
                json_files = ['file1.json', 'file2.json']

                with open('merged.json', 'w') as json_out:

                # Store updated results in this dict
                data = {}

                for file in json_files:
                with open(file, 'rb') as json_file:
                json_data = loads(json_file.read())

                # Update result dict with merged data
                data.update(merge(data, json_data))

                dump(data, json_out, indent=4)


                Which gives the following merged.json:



                {
                "head-param": "foo",
                "head-param1": "bar",
                "head-sub-param": {
                "head-sub-param1": "foo",
                "head-sub-param2": "bar"
                },
                "body": {
                "name1": {
                "value": "foo",
                "option": "bar",
                "bar": "bar",
                "foo": "foo",
                "baz": "baz"
                },
                "name22": {
                "value1": "foo1",
                "option1": "bar1",
                "bar1": "bar1",
                "foo1": "foo1",
                "baz1": "baz1"
                }
                }
                }






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 22 '18 at 11:51

























                answered Nov 22 '18 at 11:37









                RoadRunnerRoadRunner

                11.3k31340




                11.3k31340























                    1














                    You could write a little recursive function:



                    def update_nested_dict(dict_1, dict_2):
                    """Mutate dict_1 by updating it with all values present in dict_2."""
                    for key, value in dict_2.items():
                    if key not in dict_1:
                    # Just add the value to dict_1
                    dict_1[key] = value
                    continue

                    if isinstance(value, dict):
                    # If this is a dict then let's recurse...
                    update_nested_dict(dict_1[key], value)


                    Calling update_nested_dict(json1, json2) mutates json1 to:



                    {'head-param': 'foo',
                    'head-param1': 'bar',
                    'head-sub-param': {'head-sub-param1': 'foo', 'head-sub-param2': 'bar'},
                    'body': {'name1': {'value': 'foo',
                    'option': 'bar',
                    'bar': 'bar',
                    'foo': 'foo',
                    'baz': 'baz'},
                    'name22': {'value1': 'foo1',
                    'option1': 'bar1',
                    'bar1': 'bar1',
                    'foo1': 'foo1',
                    'baz1': 'baz1'}}}





                    share|improve this answer
























                    • You've basically implemented in pure Python what the built-in dict.update() method would do much more quickly.

                      – martineau
                      Nov 22 '18 at 18:12











                    • I don't think that's quite true, unless dict.update has a recursive option?

                      – Bernard Stockermans
                      Nov 23 '18 at 16:36






                    • 1





                      Bernard: No, dict.update() doesn't have an option like that—but it doesn't need one. Here's an example with some proof (in addition, of course, to my own answer to this question).

                      – martineau
                      Nov 23 '18 at 19:36


















                    1














                    You could write a little recursive function:



                    def update_nested_dict(dict_1, dict_2):
                    """Mutate dict_1 by updating it with all values present in dict_2."""
                    for key, value in dict_2.items():
                    if key not in dict_1:
                    # Just add the value to dict_1
                    dict_1[key] = value
                    continue

                    if isinstance(value, dict):
                    # If this is a dict then let's recurse...
                    update_nested_dict(dict_1[key], value)


                    Calling update_nested_dict(json1, json2) mutates json1 to:



                    {'head-param': 'foo',
                    'head-param1': 'bar',
                    'head-sub-param': {'head-sub-param1': 'foo', 'head-sub-param2': 'bar'},
                    'body': {'name1': {'value': 'foo',
                    'option': 'bar',
                    'bar': 'bar',
                    'foo': 'foo',
                    'baz': 'baz'},
                    'name22': {'value1': 'foo1',
                    'option1': 'bar1',
                    'bar1': 'bar1',
                    'foo1': 'foo1',
                    'baz1': 'baz1'}}}





                    share|improve this answer
























                    • You've basically implemented in pure Python what the built-in dict.update() method would do much more quickly.

                      – martineau
                      Nov 22 '18 at 18:12











                    • I don't think that's quite true, unless dict.update has a recursive option?

                      – Bernard Stockermans
                      Nov 23 '18 at 16:36






                    • 1





                      Bernard: No, dict.update() doesn't have an option like that—but it doesn't need one. Here's an example with some proof (in addition, of course, to my own answer to this question).

                      – martineau
                      Nov 23 '18 at 19:36
















                    1












                    1








                    1







                    You could write a little recursive function:



                    def update_nested_dict(dict_1, dict_2):
                    """Mutate dict_1 by updating it with all values present in dict_2."""
                    for key, value in dict_2.items():
                    if key not in dict_1:
                    # Just add the value to dict_1
                    dict_1[key] = value
                    continue

                    if isinstance(value, dict):
                    # If this is a dict then let's recurse...
                    update_nested_dict(dict_1[key], value)


                    Calling update_nested_dict(json1, json2) mutates json1 to:



                    {'head-param': 'foo',
                    'head-param1': 'bar',
                    'head-sub-param': {'head-sub-param1': 'foo', 'head-sub-param2': 'bar'},
                    'body': {'name1': {'value': 'foo',
                    'option': 'bar',
                    'bar': 'bar',
                    'foo': 'foo',
                    'baz': 'baz'},
                    'name22': {'value1': 'foo1',
                    'option1': 'bar1',
                    'bar1': 'bar1',
                    'foo1': 'foo1',
                    'baz1': 'baz1'}}}





                    share|improve this answer













                    You could write a little recursive function:



                    def update_nested_dict(dict_1, dict_2):
                    """Mutate dict_1 by updating it with all values present in dict_2."""
                    for key, value in dict_2.items():
                    if key not in dict_1:
                    # Just add the value to dict_1
                    dict_1[key] = value
                    continue

                    if isinstance(value, dict):
                    # If this is a dict then let's recurse...
                    update_nested_dict(dict_1[key], value)


                    Calling update_nested_dict(json1, json2) mutates json1 to:



                    {'head-param': 'foo',
                    'head-param1': 'bar',
                    'head-sub-param': {'head-sub-param1': 'foo', 'head-sub-param2': 'bar'},
                    'body': {'name1': {'value': 'foo',
                    'option': 'bar',
                    'bar': 'bar',
                    'foo': 'foo',
                    'baz': 'baz'},
                    'name22': {'value1': 'foo1',
                    'option1': 'bar1',
                    'bar1': 'bar1',
                    'foo1': 'foo1',
                    'baz1': 'baz1'}}}






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 22 '18 at 12:12









                    Bernard StockermansBernard Stockermans

                    315




                    315













                    • You've basically implemented in pure Python what the built-in dict.update() method would do much more quickly.

                      – martineau
                      Nov 22 '18 at 18:12











                    • I don't think that's quite true, unless dict.update has a recursive option?

                      – Bernard Stockermans
                      Nov 23 '18 at 16:36






                    • 1





                      Bernard: No, dict.update() doesn't have an option like that—but it doesn't need one. Here's an example with some proof (in addition, of course, to my own answer to this question).

                      – martineau
                      Nov 23 '18 at 19:36





















                    • You've basically implemented in pure Python what the built-in dict.update() method would do much more quickly.

                      – martineau
                      Nov 22 '18 at 18:12











                    • I don't think that's quite true, unless dict.update has a recursive option?

                      – Bernard Stockermans
                      Nov 23 '18 at 16:36






                    • 1





                      Bernard: No, dict.update() doesn't have an option like that—but it doesn't need one. Here's an example with some proof (in addition, of course, to my own answer to this question).

                      – martineau
                      Nov 23 '18 at 19:36



















                    You've basically implemented in pure Python what the built-in dict.update() method would do much more quickly.

                    – martineau
                    Nov 22 '18 at 18:12





                    You've basically implemented in pure Python what the built-in dict.update() method would do much more quickly.

                    – martineau
                    Nov 22 '18 at 18:12













                    I don't think that's quite true, unless dict.update has a recursive option?

                    – Bernard Stockermans
                    Nov 23 '18 at 16:36





                    I don't think that's quite true, unless dict.update has a recursive option?

                    – Bernard Stockermans
                    Nov 23 '18 at 16:36




                    1




                    1





                    Bernard: No, dict.update() doesn't have an option like that—but it doesn't need one. Here's an example with some proof (in addition, of course, to my own answer to this question).

                    – martineau
                    Nov 23 '18 at 19:36







                    Bernard: No, dict.update() doesn't have an option like that—but it doesn't need one. Here's an example with some proof (in addition, of course, to my own answer to this question).

                    – martineau
                    Nov 23 '18 at 19:36




















                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53429414%2fhow-to-merge-json-files%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    MongoDB - Not Authorized To Execute Command

                    How to fix TextFormField cause rebuild widget in Flutter

                    Npm cannot find a required file even through it is in the searched directory