Loke Cool
Loke Cool

Reputation: 35

How to merge two json object using jQuery?

I have two json objects data and foo, i want to merge them and create a single json object. The resultant json should have all the values from foo and the values from data. so far i have something like this

javascript:

  $('#btn').click(function(){
            var imdbid=$('#tst').val();
            var url = "http://www.omdbapi.com/?i="+imdbid+"&plot=full&r=json"
            $.ajax({
            url:url,
            dataType:'json',
            success:function (json) {
                 data=json
                 var foo=$('form').serializeJSON() // store json string 
                 var marged=$.extend(data,foo);
                 console.log(marged);
                }
            })   
            }) 

HTML:

<form id="myform">
<label>imdb id:</label><input type="text"  id="tst" name="tst"/></form><br/>
<label>comment:-</label><input type="text" id="comment" name="comment" /><br/>
<label>link:-</label><input type="text" name="link" id="link" /><br/>
<input type="button" value="search"  id="btn"/>
</form>

the first object contains data returned from api and foo contains the values of form.i want to marge both object on a success function and send to php. when i am trying to print out the data it's as follows

{Title: "Mother's Day", Year: "2016", Rated: "PG-13", Released: "29 Apr 2016", Runtime: "118 min"…}
Actors
:
"Britt Robertson, Jennifer Aniston, Julia Roberts, Timothy Olyphant"
Awards
:

imdbID
:
"tt4824302"
tst
:
"tt4824302"

it's getting first input value not showing the second two.

Upvotes: 1

Views: 1539

Answers (2)

Webomatik
Webomatik

Reputation: 836

You're closing the FORM on this line:

<label>imdb id:</label><input type="text"  id="tst" name="tst"/></form><br/>

... so it only gets the first input field ; )

Upvotes: 1

Naresh Teli
Naresh Teli

Reputation: 138

first change json to object than merge them as

data=json

var foo=$('form').serializeJSON();

marged=$.extend(JSON.parse(data),JSON.parse(foo));

console.log(marged);

Upvotes: 1

Related Questions