0

I've been stuck for hours, and I need your help.

The requirement is this.

Having two JSON objects, one is always the source and has all the data we need.
Second JSON object does not contain all data from source

The requirement:

This is the source JSON object.

{
  "lang": "en",
  "global": {
    "clear_search": "Clear Search",
    "filter": "Filter",
    "projects": {
        "sort_projects": "Sort projects by"
    },
  },
}

And this is the second object (NOTE: First object always contains more data):

{
  "lang": "de",
  "global": {
    "clear_search": "Suche löschen",
    "filter": "Filter",
  },
}

I need to:

  • Find difference between the source and object 2
  • Update the difference, from source to object 2
  • If property of the source is an Object, loop through it, which means if it's nested I need to loop through it, (recursion).
  • If keys are the same, but values are not, keep the keys but use the object 2 value.

    Result:

{
  "lang": "de",
  "global": {
    "clear_search": "Suche löschen",
    "filter": "Filter",
    "projects": {
        "sort_projects": "Sort projects by"
    },
  },
}

Thank you for checking this out, I kindly ask you not to post code with the variable names, like x or _.

Elvis S.
  • 362
  • 1
  • 3
  • 13

1 Answers1

0

You can represent a json in form of a tree. Every node in the tree will represent a json key. A parallel dfs from root for both the trees will help you mark the keys common to both the trees. The unmarked keys will be the difference.

You can extend this dfs traversal to further populate second json with the missing keys.

Bugman
  • 191
  • 6
  • Something like a binary tree? I've pretty much solved this problem but the issue is when I have nested object, and in a nested object same set of keys, it doesn't add up a key, in a nested parent, but it writes one level before. – Elvis S. Apr 29 '20 at 05:59
  • Not necessarily a binary tree. A node in a binary tree has two children, but in your case it can have multiple children. So just a normal tree. You can maintain a vector inside your node to maintain adjacency list. – Bugman Apr 29 '20 at 08:18
  • Do you have any example? Thanks. – Elvis S. Apr 29 '20 at 09:40