Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I include one JSON in another JSON?

Tags:

json

jquery

php

My first JSON is:

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

This will come from a java URL, here I am using PHP, in PHP I am calling a java URL.

My Second JSON is:

{"criterias":"Location"}

I am generating this using JQuery. How can I include the second JSON into the first JSON criterias?

like image 973
sreenath Avatar asked Mar 06 '14 06:03

sreenath


People also ask

How do you add two JSON objects together?

We can merge two JSON objects using the putAll() method (inherited from interface java.

Can a JSON file reference another JSON file?

JSON Reference allows a JSON value to reference another value in a JSON document. This module implements utilities for exploring these objects.

Can JSON be nested?

Objects can be nested inside other objects. Each nested object must have a unique access path. The same field name can occur in nested objects in the same document.


2 Answers

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.

like image 174
Ildar Rakhmanov Avatar answered Oct 15 '22 01:10

Ildar Rakhmanov


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);
like image 33
PressingOnAlways Avatar answered Oct 15 '22 01:10

PressingOnAlways