473,480 Members | 2,052 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Merge 2 JSON Strings, or Object Structures

2 New Member
I have the following relatively simple requirement:

I have 2 JSON strings, which contains varying nested objects. I need to merge the two strings into one string, maintaining all the hierarchies. I suspect I need some sort of recursive regular expression, but this is outside my area of expertise.

Any help is greatly appreciated.

For example:

Expand|Select|Wrap|Line Numbers
  1. var json1 = { "root": { "Company": {"Name":"CompanyName", "Address":"MainStreet"} } }
  2. var json2 = { "root": {"AnotherObj": { "Property":"Value"}, "Company" : {"Phone":"604"} }
  3.  
  4. var merged = { "root" : {"Company": {"Name":"CompanyName", "Address":"MainStreet", "Phone":"604"}, "AnotherObj": {"Property":"Value"} } }
So, The fields of the company object from the second string have been appended into company fields of the first string. I would also like to account for arrays.
Jul 18 '08 #1
3 12340
rnd me
427 Recognized Expert Contributor
far easier to eval, merge, then restringify usinf .toSource or .toJSONString() (json.js).

is that how the json has to come, or do you have some control over the way it is constructed? right now, it would be a bit of a bear, but with a few simple changes, they could easily be merged.
Jul 18 '08 #2
skbach
2 New Member
I have control over the JSON.

I'm willing to either recursively loop through the objects, or use regex to merge the strings and then eval...either way.

But I've spent all week on this damn thing and I can't do it anymore.

I'm almost there, but each solution is not quite good enough.

So, for example in the code below, the first object has an Address object with several properties, and the second object has that same Address object with different properties.

Currently, the properties of the first object are getting overriden, instead of merged.

If the properties are the same in both objects, then they can be overridden (no duplicates), but if they're different, then I'd like them to be appended...is this simple ??


The following code "almost" does what I want, but it just overwrites after the first level, so I think it needs recursion.

I'm very open to your string idea at this point.

Expand|Select|Wrap|Line Numbers
  1. var firstObj = { "Type":"1", "Company": {"CompanyAddresses":[ {"Address": {"PostalCode":"V6H1S2", "AddressLine1":"3318 Main"}}]} };
  2.                 var secondObj = { "Type":"1", "Company": {"CompanyAddresses":[ {"Address": {"AddressLine2":"#2"}}]} }

Expand|Select|Wrap|Line Numbers
  1. for(var i in objA ) {
  2.         var found = new Array();
  3.         for(var j in objB ) {
  4.             if(i==j) {
  5.                 found.push(j);
  6.                 for(var k in objB[j] ) {
  7.                     objA[i][k] = objB[j][k];
  8.                 }
  9.             }
  10.         }
  11.         for(var j in objB) {
  12.             if(found.indexOf(j) == -1) {
  13.                 objA[j] = objB[j];
  14.             }
  15.         }
  16.     }
Jul 18 '08 #3
rnd me
427 Recognized Expert Contributor
the object container really complicates it. if you can turn it into an array, it would be much simpler to use the following code in a loop:

Expand|Select|Wrap|Line Numbers
  1. Object.prototype.merge =  function (ob) {//merges and over-write left side object property with new and like properties in the passed object.
  2.         var o = this;
  3.         var i = 0;
  4.         for (var z in ob) {
  5.             if (ob.hasOwnProperty(z)) {
  6.                 o[z] = ob[z];
  7.             }
  8.         }
  9.         return o;
  10.     }
  11.  
  12. //usage examples:
  13. var one = { name:"Number One", age: 33, paid: true}
  14. var two = { age: 44, paid: true }
  15. var three = { name: "Number Three" }
  16.  
  17. one.merge(two) // ={name:"Number One", age:44, paid:true}
  18. one.merge(two).merge(three)//={name:"Number Three", age:44, paid:true}
  19.  
once youi get into the array, you can build an JSON-like object extracting all the keys you need for a custom match. then you can merge that anon object with your master object, completing the merge.

you can modify the merge proto pretty easily to make a .update (no new keys), or .renew(only new keys) methods as well.

then you just start chaining-up protos, and you are basically done.
if you flatten it to an array, you wont need recursion, or slow, fragile regexps.
Jul 19 '08 #4

Sign in to post your reply or Sign up for a free account.

Similar topics

2
1451
by: Randy Yates | last post by:
Having done a bit of Access Basic programming, I'm realizing that AB does seem to have (as much as I hate to admit it since I think it's a toy language) an advantage over C++. Let's say I have a...
2
3723
by: Kevin Newman | last post by:
Hello, I noticed that the JavaScript library for JSON posted on json.org (http://www.json.org/json.js) is modifying Object.prototype (adding a method - toJSONString). I thought this was...
0
2170
by: mbbostwick | last post by:
I have a problem with a mail merge procedure I used to use with Access '97. We recently converted to Office XP (2002) and I now have an issue I am unfamilliar with and have been unable to...
15
9019
by: hobosalesman | last post by:
Is there a function or library somewhere that merges 2 JSON data structures? For instance this: { "one": } plus { "one": } equals
3
7282
gauravgmbhr
by: gauravgmbhr | last post by:
can some one plz tell me how to merger two strings in PostgreSQL OR pl/Pgsql
2
3940
by: karafire2003 | last post by:
I've been tasked to do 2 questions. I think i got the majority of it done, but i'm having trouble. Question #1: Write a C program that accepts as input from the keyboard a floating point number, an...
1
2269
by: seth | last post by:
Hi: I'm trying to read JSON strings sent from the browser. Here is the scenario: 1. Using YUI tookit 2. sending JSON string from YUI toolkit - using the provided asyncRequest method. **I...
23
3167
by: dhtmlkitchen | last post by:
JSON We all know what it is. In ECMAScript 4, there's a JSON proposal: Object.prototype.toJSONString String.prototype.parseJSON The current proposal, String.prototype.parseJSON, returns...
2
11645
by: Wildhias | last post by:
hi guys I need some very basic advise. I've looked in the web but I can't find the information anywhere, but I am sure that it must be an easy task. lets suppose i have three varchchar2 num...
0
7041
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
6908
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7081
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6737
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
6921
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
4776
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4481
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
2995
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
1300
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.