how to include one JSON into another JSON?

The simplest way to include one file in another is to use cpp (C preprocessor).

For example, if I have test.json as

{"name":"NAME",
#include "another.json"
}

and another.json as

"inner":"value"

you should be able to obtain

$ cpp -P test.json
{"name":"NAME",
"inner":"value"
}

Of course, you will need to make sure that resulting syntax is correct by properly formatting both pieces.


I believe the original question is how to merge these 2 JSON objects within javascript. Assuming that, the answer is simple.

var firstJson = {  
  "categoryId":"Painting",  
  "subCategoryId":"Residential",  
  "alternatives":    [1,2,3,4,5],  
  "criterias":["price","quantity","yom","company"],  
  "answerss":[["1000","12343","4543","","4645646"],["12","23","34","","45"],["2014","","2000","1990","2005"],["xyz","","Abc","jkl","mno"]]  
};

var secondJson = {"criterias":"Location"};

firstJson.criterias = $.extend({},firstJson.criterias,secondJson.criterias);

You need to convert your first JSON string to object and add a new property to it.

If it is Java, you can use Google's Gson library

Gson gson = new Gson();
JsonObject jsonObj = gson.fromJson (jsonStr, JsonElement.class).getAsJsonObject();
jsonObj.add("criterias", "Location");

If it is JavaScript,

var jObj = JSON.parse(jsonString);
jObj.criterias = "Location";  //jObj.NewItem = "NewValue";

Tags:

Php

Jquery

Json