How do I include one JSON in another JSON? - 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?

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";

Here is the example of how you write nested JSON
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
For More examples visit following links:
http://www.jsonexample.com/
http://json.org/example
create nested JSON object in php?

Related

Android JSON string to JSONArray

In my project I get data from php server, this data in JSON syntax.
Then my application get this data from the server with simple http request and save that into a string. Now the problem is in the process of converting this string into JSON object and JSONArray.
Server return data -
{"lat":"35.241","lng":"76.845","name":"AAA"}{"lat":"38.247"lng":"76.852","name":"GGG"}
Get the string from the server and convert to JSON -
JSONObject jsonObject = null;
String url = "http://placePPP.com/hr.php?request=1";
String response = MyHttpRequest(url);
try {
jsonObject = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
The response data equal to the Server return data (there is no problem), But after the conversion to the JSON I get only the first part of the string I try to convert -
{"lat":"35.241","lng":"76.845","name":"AAA"}
I would love if someone can help me to understand why I get only the first part and how can I convert this string into a JSON object and to JSONArray in the best way thanks.
It is a malformed JSON, that's why you only have the first part.
Look at this comment for more details.
It's not valid JSON, you have two json objects next to each other.
talk with developer to send data in object or then your data as
jsonMainobject {
{"lat":"35.241","lng":"76.845","name":"AAA"}{"lat":"38.247"lng":"76.852","name":"GGG"}
}
or you can done as
jsonarray[
{"lat":"35.241","lng":"76.845","name":"AAA"}{"lat":"38.247"lng":"76.852","name":"GGG"}
]
Change string from
{"lat":"35.241","lng":"76.845","name":"AAA"}{"lat":"38.247"lng":"76.852","name":"GGG"}
to
[{
"lat": "35.241",
"lng": "76.845",
"name": "AAA"
},
{
"lat": "38.247",
"lng": "76.852",
"name": "GGG"
}]
For check valid json can use this link : http://www.jsoneditoronline.org/
Your server is not producing valid JSON response. Check here https://jsonformatter.curiousconcept.com/
Valid response would look like this:
[
{"lat":"35.241", "lng":"76.845", "name":"AAA"},
{"lat":"38.247", "lng":"76.852", "name":"GGG"}
]
Also parse it with JsonArray to get an array of two JsonObjects inside.

Empty $_POST Array parsing JS Object to PHP via JSON

I assume some of you might be already rolling their eyes since my topic has been dealt with so often in this forum. However, I haven't found any solution yet in this forum.
I want to parse a JS Object to a receiving PHP Site via JSON. I already read numerous times about the right parameters for the XMLHttpRequest-Header and its impact on the PHP part. I tried the very same solutions given in several other forums, but IT SIMPLY DOESN'T WORK for me. I've been working on this whole issue for four month now. I really need some advice.
Here is my JSON encoding JS Script:
function saveToDB(knotItems) {
var txtobj = knotItems;
var json = JSON.stringify(txtobj);
var url = "http://localhost/projektplaner/tools/DBConnection/writeFileToDB.php";
rq = new XMLHttpRequest();
rq.open("post", url, true);
rq.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
rq.send("project=" + json);
rq.onreadystatechange = window.open(url);
}
This is the JS-generated object array knotItems after being stringified by JSON:
[{
"rank": 1,
"name": "Baugrube",
"faz_obj": "2016-05-30T17:52:16.402Z",
"fazInDays": null,
"faz_string": "19.5.2016",
"faz_timestamp": 1463680336402,
"d": "2",
"parallelTask": "seriell",
"fez": ["2016-05-21T17:52:16.402Z", "21.5.2016", "NaN2"],
"fez_dateObj": "2016-05-21T17:52:16.402Z",
"fez_string": "21.5.2016"
}, {
"rank": 2,
"name": "Kellerwände",
"faz_obj": "2016-05-30T17:52:16.402Z",
"fazInDays": null,
"faz_string": "21.5.2016",
"faz_timestamp": 1463853136402,
"d": "4",
"parallelTask": "seriell",
"fez": ["2016-05-25T17:52:16.402Z", "25.5.2016", "NaN4"],
"fez_dateObj": "2016-05-25T17:52:16.402Z",
"fez_string": "25.5.2016"
}, {
"rank": 3,
"name": "Kellerdecke",
"faz_obj": "2016-05-30T17:52:16.402Z",
"fazInDays": null,
"faz_string": "25.5.2016",
"faz_timestamp": 1464198736402,
"d": "5",
"parallelTask": "seriell",
"fez": ["2016-05-30T17:52:16.402Z", "30.5.2016", "NaN5"],
"fez_dateObj": "2016-05-30T17:52:16.402Z",
"fez_string": "30.5.2016"
}]
The reason I post the variable content is to show that all object keys are in double quotes, as required by PHP's json_decode.
This is my PHP receiving script:
if(isset($_POST['project']))
{
echo json_decode($_POST['project'],true);
}
else
{
echo "Keine Daten"; // No Data
}
This is the parameter payload that can be seen via Firebug analysis:
project:"[{"rank":1,"name":"Baugrube","faz_obj":"2016-05-30T17:52:16.402Z","fazInDays":null,"faz_string":"19.5.2016","faz_timestamp":1463680336402,"d":"2","parallelTask":"seriell","fez":["2016-05-21T17:52:16.402Z","21.5.2016","NaN2"],"fez_dateObj":"2016-05-21T17:52:16.402Z","fez_string":"21.5.2016"},{"rank":2,"name":"Kellerwände","faz_obj":"2016-05-30T17:52:16.402Z","fazInDays":null,"faz_string":"21.5.2016","faz_timestamp":1463853136402,"d":"4","parallelTask":"seriell","fez":["2016-05-25T17:52:16.402Z","25.5.2016","NaN4"],"fez_dateObj":"2016-05-25T17:52:16.402Z","fez_string":"25.5.2016"},{"rank":3,"name":"Kellerdecke","faz_obj":"2016-05-30T17:52:16.402Z","fazInDays":null,"faz_string":"25.5.2016","faz_timestamp":1464198736402,"d":"5","parallelTask":"seriell","fez":["2016-05-30T17:52:16.402Z","30.5.2016","NaN5"],"fez_dateObj":"2016-05-30T17:52:16.402Z","fez_string":"30.5.2016"}]"
HTTP Status Code is always 200 (OK).
And this is what I get from the PHP File.
Notice: Undefined index: project in C:\xampp\htdocs\projektplaner\tools\DBConnection\writeFileToDB.php on line 7
Keine Daten
I don't want to sound melodramatic or anything, but I'm about to go ape. I just can't see what the hell is wrong. Could it be a Server configuration issue?
I really, really appreciate your help.
Thank you very much in advance.

Using JSON in PHP to send data to Android

I'm not sure that the JSON codes i have used in my PHP is right to send the data to my Android App. My Android app works fine without any errors. I'm using Async Task to retrieve information from the server using JSON.
This is the code i have used in my Android app to get information from server :
JSONArray arr = new JSONArray(result);
JSONObject jObj = arr.getJSONObject(0);
myoutput = jObj.getString("stringpval");
I havn't displayed the entire code, but i'm sure that all the other codes work fine.
And below is my PHP script used to create a JSON array in PHP:
$a = array(
array('stringpval' => "My Value"));
print $json = json_encode($a);
So i have finished encoding json. I want my TextView in android to display "My Value"! Now when i run my android app and try to get the information from the server, my TextView goes blank. It is Null! What's the problem? Any Solution? Are the above codes correctly used?
The reason is that json_encode($a); is actually returning a JSONObject and not just a JSONArray as you're thinking.
What you're currently printing will look like this:
{
{
'stringpval' = "My Value"
}
}
I'm not sure why you're using a double-array for passing back a single value like that, so for now I would change your PHP file to:
$a = array('stringpval' => "My Value");
print $json = json_encode($a);
Which will return:
{
'stringpval' = "My Value"
}
Which you could then access in Java by:
JSONObject jObj = new JSONObject(result);
myoutput = jObj.getString("stringpval");
json usually is in two forms, either objects, or arrays, this is very important because you have to know which values are you retrieving from the server(json array or json object?) and hence parse them in the correct manner in the client side.
JsonArray are usually like this
{
"jsonarray_example": [
{
"id": "1",
"name": "android",
"description": "android 4.4.3 kitkat",
"updated_at": "0000-00-00 00:00:00"
} ,
{
"id": "2",
"name": "android",
"description": "android 4.1 jellybin",
"updated_at": "0000-00-00 00:00:00"
}
]
}
The opening and closing [] marks the array while the {} brackets marks the objects of the array called jsonarray_example but the brackets need not be like that now if your php page outputs something like that then you can retrieve the array else you have to retrieve the objects JsonObject in android
so from your problem above you are trying to retrieve jsonObjects while your response is array you should use something like
JsonArray result = new JsonArray() ;
JsonObject obj = //access the server files
result = obj.getJsonArray("stringpval") ;
// proceed extracting individual content from the response
for more check this LINK and this ONE can be really helpful

how to remove "result": "success" on json callback

The result of the call to the api server is a json file, which begins with this string:
{
"result": "success"
, "data": {"total":16080,"pageCount":161,"result":[{"packWidth":250,"itemNo"
How do I remove the part that I do not care?
that is, this
{
"result": "success"
, "data": {"total":16080,"pageCount":161,"result":
The complete result is:
{
"result": "success"
, "data": {"total":16080,"pageCount":161,"result": [{"packWidth":250,"itemNo":"1203945","groupItemNo":"1203945","status":1,"categoryId":105096,"packType":"Color Box","barcode":"6922833439687","modelLabel":"Color","packQty":24,"packInclude":"USB Cable, User Manual, USB Charger, Earphone, 1pcs Li-Battery, LCD Protector, Leather Case, Plastic Case","clearance":false,"id":103928,"packWeight":"12.500","price":"181.2800","packLength":400,"description":"description test","unitWeight":"0.726","packHeight":300}]}}
I use the PHP language
I have to remove the initial part:
{
"result": "success"
, "data": {"total":16080,"pageCount":161,"result":
and the final:
}}
If you want to use part of a JSON to populate a CSV file, then parse the json using json_decode method and access the necessary information.
Try something like this:
var jsonObject = json_decode(myJson);
var interestingPart = jsonObject.data.result;
You can now access the data in an Object manner. Or if you want to get a json back from it, then use:
var interestingJson = json_encode(interestingPart);
Not tested, but it should work
preg_replace("/^.*?:(?=\w*\[) | (\w*}\w*}\w*$)/", "", $str);
Edit: i wrote this before I knew of json_decode, you should really use the json functions like suggested in fazovskys answer.

creating json array from arraylist android

I've been toying around with this for a little while and I'm looking for some help. I have an ArrayList that I turn into a JSONArray and then place inside JSONObject. The problem is my formatting. Allow me to show you.
I get the values for my ArrayList and add them like so (small code snippet)
if (v instanceof EditText) {
String answer = ((EditText) v).getText().toString();
if (answer.equals("")) {
error.setText(v.getTag().toString()
+ " Needs an answer");
((EditText) v).setHint("Fill me out!");
((EditText) v).setHintTextColor(getResources()
.getColor(R.color.red_bg));
} else {
error.setText("");
}
String question = v.getTag().toString();
String combo = question + ": " + answer;
myList.add(combo);
Log.v("INFO", "Storing: " + combo);
}
This works, but adding the ":" is the start of my problems. The log prints out
06-19 12:13:33.630: V/INFO(3272): Storing: Height: 6`4
Now when I create my JSON to be sent over I use the following
if (error.getText().toString().equals("")) {
JSONObject json = new JSONObject();
JSONArray jArray = new JSONArray(myList);
try {
json.putOpt("array", jArray);
} catch (JSONException e) {
e.printStackTrace();
}
Again, this works. Now the problem clearly illustrated, it prints out JSON like this
{
"array":
[
"Store #: 00608",
"Phone #: null",
"Address: 3014 N. SCOTTSDALE RD.",
"City: SCOTTSDALE",
"Zip: 85251",
"State: AZ",
"Height: 6`4",
"Weight: 230",
"Ethnicity: White",
"Age: 23",
"Eye Color: Blue",
"Favorite Food: Thai",
"Comments: awesome"
]
}
If you're familiar with JSON you know I've goofed it here. I was merely trying to keep the question and answer together. However by adding the ":" to the middle it looks like I'm trying to use question as the key and answer as the value (kind of). Anyways in the end this looks like legitimate JSON, and it is, but it doesn't work the way I need it to.
My question is, should I just make "question" the key, and "answer" the value?
If so how would I go about creating my JSONArray so that my JSON looks like this
{
"array":
[
"Store #" : "00608",
"Phone #" : "null",
"Address" : "3014 N. SCOTTSDALE RD.",
"City" : "SCOTTSDALE",
"Zip" : "85251",
"State" : "AZ",
"Height" : "6`4",
"Weight" : "230",
....
]
}
So that a simple
var_dump(json_decode($json));
var_dump(json_decode($json, true));
in PHP will provide me with the data I need server side.
or alternatively would it just be simpler to keep this format and split the strings as I parse them server side? Whichever answer you choose please supply a few lines of code with to illustrate your answer. As you can tell I'm a visual person.
Thanks for the help, I hope this helps other people in the future as well!
You can solve this a bunch of ways. If you want to keep the formatting the way it is you just need to process your strings first. When you get values from your ArrayList just split the combo into parts
int splitPoint = combo.indexOf(":")
String key = combo.substring(0, splitPoint);
String value = combo.substring(splitPoint + 1);
Once you split the key and value out just create a new JSONObject and add the key and value as a string
JSONObject jObject = new JSONObject();
jObject.put(key, value);
This will add the JSONString to its own JSONObject. Then you can add this object to the JSONArray that you want to create
JSONArray jArray = new JSONArray();
jArray.puJSONObject(jObject);
I broke this down in to parts but if you just decalre your JSONArray ouside a for loop or some other iterator and loop through your ArrayList, processing each combo string and adding the resulting object to a JSONArray you can acheive the desired result
I am not sure that you can do the following in JSON
[ "key":"value, ...."].
You may be able to do it with Key Value object pairs, as in
[ {"key":"value"},...]
If you do it with objects, you will have to create a new object for each pair, and it might become pretty complicated since the key in JSON corresponds with the name of an instance variable.
My suggestion is to leave it the way you have it now and split the strings. I am not familiar with PHP, but it should be as simple as looping through the JSON array and calling something like split(':') on the strings.
You can make a JSONObject with dynamic keys like so:
{
"Store #" : "00608",
"Phone #" : "null",
"Address" : "3014 N. SCOTTSDALE RD.",
"City" : "SCOTTSDALE",
"Zip" : "85251",
"State" : "AZ",
"Height" : "6`4",
"Weight" : "230",
....
}
The question what is simpler, can only be answered by you yourself, as obviously you implement the App and the Server part. So whatever works best for you is the right way.
Performance-wise, joining strings on one side and splitting them on the other side is not the best, but it also depends on how many entries there are in your array.

Categories