问题
I tried to merge two json both with $.extend
and $.merge
but no success. I also tried to attach it like this:
data: JSON.stringify({"data" : [
{term: request.term},
jsontag
]}),
Here's my setup:
autocomplete: ({
source: function (request, response) {
var tags = $('#input-newsearch-2').val();
var jsonfied = {
tags: tags.replace(/,$/, "").split(",").map(function (tag) {
return { tag: tag };
})
};
var jsontag = JSON.stringify(jsonfied);
var jsonterm = JSON.stringify({ term: request.term });
//console.log(jsontag);
//console.log(jsonterm);
//var mergedObj = $.extend(jsontag, jsonterm);
//console.log(mergedObj);
$.ajax({
url: "/source",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: [jsontag, jsonterm],
success: function (data) {
response(data);
}
});
},
});
Console:
{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]}
{"term":"value04"}
I was hoping to get sth like:
[{"term":"value04"},{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]}]
Or even better:
{"data":[{"term":"value04"},{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]}]}
回答1:
You can simply do this, and achieve what you desire.
const mergedJSON = {data: []};
mergedJSON.data.push(jsonterm);
mergedJSON.data.push(jsontag);
console.log(JSON.stringify(mergedJSON));
And output will be
{"data":[{"term":"value04"},{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]}]}
Which fits your even better scenario. Check this jsFiddle for demo.
回答2:
What about using Lodash js library for manipulating arrays, objects, ...
回答3:
So what seems to work is if I first merge the arrays and then JSON.stringify() it ... like ..
var jsontag = { data };
var jsonterm = {};
jsonterm['terms'] = { term: request.term };
console.log(jsontag);
console.log(jsonterm);
var mergedJSON = JSON.stringify($.extend(true, jsontag, jsonterm));
console.log(mergedJSON);
JSON result:
{"data":{"tags":[{"tag":"value04"},{"tag":"value03"},{"tag":"value02"}]},"terms":{"term":"value01"}}
来源:https://stackoverflow.com/questions/43122479/merging-two-json-deep-nested