1

I'm writing a method which should concatenate two strings(that are result of json stringify) into one string(which should look like json object with it's structure).

First one :

{"text":"klk","makeId":"9"}

Second one:

{"firstname":"jjk","lastname":"jkjk","email":"[email protected]"}

How do I concatenate these two into one json string i.e :

{"text":"klk","makeId":"9", "firstname":"jjk","lastname":"jkjk","email":"[email protected]"}

I could strip {" and "} then split by comma and achieve this result. I'm wondering is there better more smart way to do this?

2
  • 2
    Don't use string concatenation. Parse the JSON, consolidate the objects' content, and serialize the result. Commented Nov 28, 2012 at 17:14
  • @hall.stephenk no issues, it's just ugly code Commented Nov 28, 2012 at 17:16

1 Answer 1

6

These strings are JSON! Parse them, merge them like objects and stringify them again.


var data1 = JSON.parse(json1);
var data2 = JSON.parse(json2);
var data = merge(data1, data2); // implement merge!
console.log(JSON.stringify(data));

JSON should be available in all recent browsers.

function merge(obj1, obj2) {
    var hasOwn = {}.hasOwnProperty;
    for (var key in obj2) {
        if (hasOwn.call(obj2, key)) {
            obj1[key] = obj2[key];
        }
    }
    return obj1;
}
Sign up to request clarification or add additional context in comments.

3 Comments

I agree, but I cannot give you a +1 because "implement merge" is a pretty big step if the OP is not a JavaScript expert.
@SAJ14SAJ Not really. I'm by no means a JavaScript expert (with that I mean, I've written Hello World and that's basically it) and I could do it in less than 5 minutes.
@Cubic If you know about hasOwnProperty, and finding an guaranteed unmodified version of it, then you are definitely closer to expert than novice :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.