JSON sending fine as key:answer, not key:array - php

I'm having an issue where my android application is getting a positive result from our key:answer POST, but not from key:array for the same structure. My web developer is saying that I'm not serialising it properly, but every JSON tester I can find on the web is quite happy with the send, just not our web server. I'm sending my JSON in groups of 10 as a string (We had a previous issue where when sending about 200 keys it was giving issues, so I've split it down to 10 per send) and the JSON sent is as follows:
[{
"jobDetails": {
"jobid": "7",
"company": {
"cmid": "30"
}
},
"formName": "IPE Report",
"formHeader": "Activity",
"key": "date_inspDate",
"answervalues": "18-07-2017"
}, {
"jobDetails": {
"jobid": "7",
"company": {
"cmid": "30"
}
},
"formName": "IPE Report",
"formHeader": "Activity",
"key": "text_clientRep",
"answervalues": "testrep"
}, {
"jobDetails": {
"jobid": "7",
"company": {
"cmid": "30"
}
},
"formName": "IPE Report",
"formHeader": "Activity",
"key": "text_designCode",
"answervalues": "destdesign"
}, {
"jobDetails": {
"jobid": "7",
"company": {
"cmid": "30"
}
},
"formName": "IPE Report",
"formHeader": "Activity",
"key": "text_qcPlan",
"answervalues": "testqc"
}, {
"jobDetails": {
"jobid": "7",
"company": {
"cmid": "30"
}
},
"formName": "IPE Report",
"formHeader": "Activity",
"key": "text_equipDesc",
"answervalues": "testdesc"
}, {
"jobDetails": {
"jobid": "7",
"company": {
"cmid": "30"
}
},
"formName": "IPE Report",
"formHeader": "Activity",
"key": "text_companyName",
"answervalues": "testco"
}, {
"jobDetails": {
"jobid": "7",
"company": {
"cmid": "30"
}
},
"formName": "IPE Report",
"formHeader": "Activity",
"key": "text_drawingNo",
"answervalues": "testrev"
}, {
"jobDetails": {
"jobid": "7",
"company": {
"cmid": "30"
}
},
"formName": "IPE Report",
"formHeader": "Activity",
"key": "Detail",
"answervalues": [{
"register": 1,
"values": "act2"
}, {
"register": 2,
"values": "act3"
}]
}, {
"jobDetails": {
"jobid": "7",
"company": {
"cmid": "30"
}
},
"formName": "IPE Report",
"formHeader": "Activity",
"key": "Regulated",
"answervalues": [{
"register": 1,
"values": "YES"
}, {
"register": 2,
"values": "NO"
}]
}, {
"jobDetails": {
"jobid": "7",
"company": {
"cmid": "30"
}
},
"formName": "IPE Report",
"formHeader": "Activity",
"key": "Comments",
"answervalues": [{
"register": 1,
"values": "DIMENSIONS CHECK"
}, {
"register": 2,
"values": "HOLD POINT"
}]
}]
All is fine until it hits the Detail key, which is an array. This structure was sending fine last week, they claim they've changed nothing. Is it really a serialisation issue on my side or is the server just not accepting that key as either value or array?

From your error message:
"JSON parse error: Can not deserialize instance of java.lang.String out of START_ARRAY token;"
I think you problem is in 'answervalues'.
/* in some entries you have it as an array of objects*/
"answervalues": [{
"register": 1,
"values": "YES"
}, {
"register": 2,
"values": "NO"
}]
/* while in other entries as a string */
"answervalues": "testrev"
Talk with your developer to see how this need to be formatted. I believe the string values also need to be passed as an object in a single array. Something like..
"answervalues": [{
"register": 1,
"values":"testrev"
}]

Related

Extract element from nested JSON

There is json response:
{
"id": "1234567890123456789",
"creation_date": 12345678,
"event": "WAITING_PAYMENT",
"version": "2.0.0",
"data": {
"product": {
"id": 213344,
"name": "Product Name",
"has_co_production": false
},
"affiliates": [
{
"name": "Affiliate name"
}
],
"buyer": {
"email": "buyer#email.com"
},
"producer": {
"name": "Producer Name"
},
"commissions": [
{
"value": 0.65,
"source": "MARKETPLACE"
},
{
"value": 3.10,
"source": "PRODUCER"
}
],
"purchase": {
"approved_date": 1231241434453,
"full_price": {
"value": 134.0
},
"original_offer_price": {
"currency_value": "EUR"
"value": 100.78,
},
"price": {
"value": 150.6
},
"order_date": "123243546",
"status": "STARTED",
"transaction": "HP02316330308193",
"payment": {
"billet_barcode": "03399.33335 33823.303087 198801027 2 876300015000",
"billet_url": "https://billet-link.com/bHP023163303193",
}
},
"subscription": {
"status": "ACTIVE",
"plan": {
"name": "plan name"
},
"subscriber": {
"code": "12133421"
}
}
}
}
My question is how to extract data["buyer"]["email"] in PHP ?
I only need to extract the email information from the buyer table inside the data table.
First, you need to decode the json to a PHP array (or an object), then you can access the requested information from the decoded data.
$data = json_decode('the json string most place here', true);
$email = $data['buyer']['email'];
Place your json string in the first argument of json_decode() function.

Get the values in PHP of three objects in Tripadvisor JSON API file

Been struggling with this for too long now, so am kindly asking for your help.
How can I, using PHP, get the values of the text fields in the reviews of which there are three in this JSON file below.
Want to use a foreach loop for this, thanks for helping me out!
{
"address_obj": {
"street1": "Rustenburgerstreet 384",
"street2": null,
"city": "Amsterdam",
"state": "North Holland Province",
"country": "The Netherlands",
"postalcode": "1072 HG",
"address_string": "Rustenburgerstreet 384, 1072 HG Amsterdam The Netherlands"
},
"percent_recommended": null,
"latitude": "52.35162",
"rating": "5.0",
"attraction_types": [
{
"name": "concerts",
"localized_name": "Concerts"
},
{
"name": "blues bars",
"localized_name": "Blues Bars"
},
{
"name": "jazz bars",
"localized_name": "Jazz Bars"
},
{
"name": "bar/ clubs",
"localized_name": "Bars & Clubs"
}
],
"wikipedia_info": null,
"location_id": "3724036",
"review_rating_count": {
"1": "0",
"2": "0",
"3": "1",
"4": "4",
"5": "35"
},
"ranking_data": {
"ranking_string": "#12 of 73 Theater & Concerts in Amsterdam",
"ranking_out_of": "73",
"geo_location_id": "188590",
"ranking": "12",
"geo_location_name": "Amsterdam"
},
"photo_count": "35",
"location_string": "Amsterdam, North Holland Province",
"trip_types": [
{
"name": "business",
"value": "0",
"localized_name": "Business"
},
{
"name": "couples",
"value": "8",
"localized_name": "Couples"
},
{
"name": "solo",
"value": "7",
"localized_name": "Solo travel"
},
{
"name": "family",
"value": "0",
"localized_name": "Family"
},
{
"name": "friends",
"value": "21",
"localized_name": "Friends getaway"
}
],
"web_url": "Attraction_Review-g188590-d3724036-Reviews-m34757-CC_Music_Cafe-Amsterdam_North_Holland_Province.html",
"reviews": [
{
"id": "353301385",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-03-06T05:20:19-0500",
"rating": 5,
"helpful_votes": "0",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r353301385-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review353301385",
"trip_type": "Solo travel",
"travel_date": "2016-02",
"text": "I am a regular visitor of CC Muziekcafé Amsterdam but have felt at home from the very first time. What I like about CC is the atmosphere where great music and hospitality are mixed in the best way...",
"user": {
"username": "Yvon H",
"user_location": {
"name": "Groningen Province, The Netherlands",
"id": "188570"
}
},
"title": "A great place to hear live music and meet all sorts of interesting people, both local and traveling",
"is_machine_translated": false
},
{
"id": "351658487",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-02-28T11:13:12-0500",
"rating": 5,
"helpful_votes": "0",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r351658487-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review351658487",
"trip_type": "Friends getaway",
"travel_date": "2016-02",
"text": "4th time we have been here, another great night at the music cafe, friendly people and a barman who knows how to just put enough swear words in to sound cool",
"user": {
"username": "Francois S",
"user_location": {
"name": "Cardiff, United Kingdom",
"id": "186460"
}
},
"title": "Jazz funk Jam session night Thursday",
"is_machine_translated": false
},
{
"id": "350605184",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-02-24T10:18:57-0500",
"rating": 5,
"helpful_votes": "1",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r350605184-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review350605184",
"trip_type": "Couples",
"travel_date": "2015-09",
"text": "CC muziekcafe is a very cosy place with excellent live music and interaction with the musicians. What really makes the place is the owner Rene who knows a lot about music and now and then even sings...",
"user": {
"username": "ImagineNL",
"user_location": {
"name": "Schagen, The Netherlands",
"id": "609049"
}
},
"title": "Cupid",
"is_machine_translated": false
}
],
You can use this code
<?php
$json = <<<EOF
{
"address_obj": {
"street1": "Rustenburgerstreet 384",
"street2": null,
"city": "Amsterdam",
"state": "North Holland Province",
"country": "The Netherlands",
"postalcode": "1072 HG",
"address_string": "Rustenburgerstreet 384, 1072 HG Amsterdam The Netherlands"
},
"percent_recommended": null,
"latitude": "52.35162",
"rating": "5.0",
"attraction_types": [
{
"name": "concerts",
"localized_name": "Concerts"
},
{
"name": "blues bars",
"localized_name": "Blues Bars"
},
{
"name": "jazz bars",
"localized_name": "Jazz Bars"
},
{
"name": "bar/ clubs",
"localized_name": "Bars & Clubs"
}
],
"wikipedia_info": null,
"location_id": "3724036",
"review_rating_count": {
"1": "0",
"2": "0",
"3": "1",
"4": "4",
"5": "35"
},
"ranking_data": {
"ranking_string": "#12 of 73 Theater & Concerts in Amsterdam",
"ranking_out_of": "73",
"geo_location_id": "188590",
"ranking": "12",
"geo_location_name": "Amsterdam"
},
"photo_count": "35",
"location_string": "Amsterdam, North Holland Province",
"trip_types": [
{
"name": "business",
"value": "0",
"localized_name": "Business"
},
{
"name": "couples",
"value": "8",
"localized_name": "Couples"
},
{
"name": "solo",
"value": "7",
"localized_name": "Solo travel"
},
{
"name": "family",
"value": "0",
"localized_name": "Family"
},
{
"name": "friends",
"value": "21",
"localized_name": "Friends getaway"
}
],
"web_url": "Attraction_Review-g188590-d3724036-Reviews-m34757-CC_Music_Cafe-Amsterdam_North_Holland_Province.html",
"reviews": [
{
"id": "353301385",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-03-06T05:20:19-0500",
"rating": 5,
"helpful_votes": "0",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r353301385-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review353301385",
"trip_type": "Solo travel",
"travel_date": "2016-02",
"text": "I am a regular visitor of CC Muziekcafé Amsterdam but have felt at home from the very first time. What I like about CC is the atmosphere where great music and hospitality are mixed in the best way...",
"user": {
"username": "Yvon H",
"user_location": {
"name": "Groningen Province, The Netherlands",
"id": "188570"
}
},
"title": "A great place to hear live music and meet all sorts of interesting people, both local and traveling",
"is_machine_translated": false
},
{
"id": "351658487",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-02-28T11:13:12-0500",
"rating": 5,
"helpful_votes": "0",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r351658487-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review351658487",
"trip_type": "Friends getaway",
"travel_date": "2016-02",
"text": "4th time we have been here, another great night at the music cafe, friendly people and a barman who knows how to just put enough swear words in to sound cool",
"user": {
"username": "Francois S",
"user_location": {
"name": "Cardiff, United Kingdom",
"id": "186460"
}
},
"title": "Jazz funk Jam session night Thursday",
"is_machine_translated": false
},
{
"id": "350605184",
"lang": "en",
"location_id": "3724036",
"published_date": "2016-02-24T10:18:57-0500",
"rating": 5,
"helpful_votes": "1",
"rating_image_url": "img/cdsi/img2/ratings/traveler/s5.0-34757-5.png",
"url": "ShowUserReviews-g188590-d3724036-r350605184-CC_Music_Cafe-Amsterdam_North_Holland_Province.html#review350605184",
"trip_type": "Couples",
"travel_date": "2015-09",
"text": "CC muziekcafe is a very cosy place with excellent live music and interaction with the musicians. What really makes the place is the owner Rene who knows a lot about music and now and then even sings...",
"user": {
"username": "ImagineNL",
"user_location": {
"name": "Schagen, The Netherlands",
"id": "609049"
}
},
"title": "Cupid",
"is_machine_translated": false
}
]
}
EOF;
$array = json_decode($json, true);
$texts = array_map(
function($item) {
return $item['text'];
}, $array['reviews']
);
It doesn't seem like you need a foreach to fetch the reviews element. Not sure if I understood your question correct, but did you want something like this:
$assoc_json = json_decode($your_json, true);
var_dump($assoc_json['reviews']);
The above turns your json into an associative array, and just access the review element.
A simple, naive approach would be:
//Loads your json file 'tripadvisor' into jsonString
$jsonString = file_get_contents("/tripadvisor.json");
//Turns your string into an associative array
$tripJsonAssoc = json_decode($jsonString, true);
//Iterate through each review and store it in result
$result = array();
foreach($tripJsonAssoc['reviews'] as $review) {
$result[] = array('text' => $review['text'],
'rating' => $review['rating']);
}
//Do what you need to do with result
//...
Or you can just do your own stuff inside the foreach loop.
This answer gives you another way (more elegant) to create the 'result' array, but since you asked for a 'foreach', I thought I would add my 5 cents.

Making a tree map with JSON data (Highcharts)

I am trying to bring data from the database to this Highcharts tree map, I have no idea how to format the JSON part of the code. When there is a clear xAxis and yAxis it is relatively easy. We use a php assembler to get all of the data from the query. I took the code straight from a Highcharts column chart with JSON that was working normally, I tried myself to update it and it keeps telling me the $.getJSON bit is an unexpected identifier.
$(function () {
// Drop-in fix:
Highcharts.seriesTypes.treemap.prototype.getExtremesFromAll = true;
$('#container').highcharts({
colorAxis: {
minColor: ' #000000',
maxColor: '#ffffff'
},
tooltip: {
backgroundColor: '#fffff',
formatter: function () {
return this.point.name + ":" + this.point.value;
}
}
$.getJSON("/charts/data/homepage-charts-data.php?<?php echo $_SERVER['QUERY_STRING']; ?>", function(json) {
options.categories = json[0]['data'];
options.series[0] = json[1];
chart = new Highcharts.Chart(options);
});
});
});
The code that formats the data (from: /charts/data/homepage-charts-data.php)
function displayJsonHomepageBallotMeasuresDataChart ($aaQuery) {
global $NIMSPv4;
$result = $NIMSPv4->query("$aaQuery");
$categories = array();
$categories['name'] = 'Election_Jurisdiction';
$series = array();
$series['name'] = 'Total_$';
while($row = $result->fetch_assoc()) {
$categories['data'][] = $row['Election_Jurisdiction'];
$series['data'][] = $row['Total_$'];
}
$result = array();
array_push($result,$categories);
array_push($result,$series);
print json_encode($result, JSON_NUMERIC_CHECK);
} // END CHART FUNCTION
Update: Here is the JSON I am trying to pull data from. Election_Jurisdiction and Total_$ is what I am trying to access for now, Candidate and Office_Sought could also be brought down as well considering it is a tree map and I will need to show the race.
{
"metaInfo": {
"format": "json",
"completeness": {
"allReports": "297",
"availableReports": "297",
"completeReports": "300",
"incompleteAvailable": "-3",
"lastUpdated": "2015-11-04 09:23:28",
"mostRecentReportDate": "2013-01-31"
},
"paging": {
"pageLink": "p=0",
"minPage": 0,
"currentPage": 0,
"maxPage": 0,
"totalPages": 1,
"totalRecords": "3",
"recordsPerPage": 100,
"recordsThisPage": 3
},
"grouping": {
"groupLink": "gro=c-t-id",
"currentGrouping": {
"c-t-id": "Candidate (General)"
},
"availableGrouping": {
"f-s": "Filing Jurisdiction (General)",
"f-eid": "Filer (General)",
"f-y": "Filing Year (Advanced)",
"c-t-i": "Incumbency Data (Advanced)",
"c-t-icod": "Incumbency Advantage (Advanced)",
"d-nme": "Original Name (Advanced)",
"d-amt": "Amount (Advanced)",
"d-dte": "Date (Advanced)",
"d-ludte": "Last Updated (Advanced)",
"d-typ": "Type of Transaction (Advanced)",
"d-llink": "Lobbying Entity? (Advanced)",
"d-ad-str": "Street (Advanced)",
"c-t-sts": "Status of Candidate (Candidates)",
"d-id": "Record (Contributors)",
"d-eid": "Contributor (Contributors)",
"d-et": "Type of Contributor (Contributors)",
"d-ccg": "Broad Sector (Contributors)",
"d-cci": "General Industry (Contributors)",
"d-ccb": "Specific Business (Contributors)",
"d-ad-cty": "City (Contributors)",
"d-ad-st": "State (Contributors)",
"d-ad-zip": "Zip (Contributors)",
"d-ins": "In-Jurisdiction (Contributors)",
"d-empl": "Employer (Contributors)",
"d-occupation": "Occupation (Contributors)"
}
},
"sorting": {
"sortLink": "so=u-tot&sod=0",
"currentSorting": {
"u-tot": "Total_$"
},
"sortingDirection": "descending",
"availableSorting": {
"c-t-id": "Candidate",
"c-t-pt": "Specific_Party",
"c-t-p": "General_Party",
"s": "Election_Jurisdiction",
"y": "Election_Year",
"c-r-t": "Election_Type",
"c-r-osid": "Office_Sought",
"c-t-ftsts": "Election_Status",
"c-t-ico": "Incumbency_Status",
"u-rec": "#_of_Records"
}
},
"recordFormat": {
"request": "c-r-id=16739",
"Candidate": {
"token": "c-t-id",
"id": "token value",
"Candidate": "display value"
},
"Candidate_Entity": {
"token": "c-t-eid",
"id": "token value",
"Candidate_Entity": "display value"
},
"Specific_Party": {
"token": "c-t-pt",
"id": "token value",
"Specific_Party": "display value"
},
"General_Party": {
"token": "c-t-p",
"id": "token value",
"General_Party": "display value"
},
"Election_Jurisdiction": {
"token": "s",
"id": "token value",
"Election_Jurisdiction": "display value"
},
"Election_Year": {
"token": "y",
"id": "token value",
"Election_Year": "display value"
},
"Election_Type": {
"token": "c-r-t",
"id": "token value",
"Election_Type": "display value"
},
"Office_Sought": {
"token": "c-r-osid",
"id": "token value",
"Office_Sought": "display value"
},
"Election_Status": {
"token": "c-t-ftsts",
"id": "token value",
"Election_Status": "display value"
},
"Incumbency_Status": {
"token": "c-t-ico",
"id": "token value",
"Incumbency_Status": "display value"
},
"#_of_Records": {
"#_of_Records": "display value"
},
"Total_$": {
"Total_$": "display value"
}
}
},
"records": [
{
"record_id": 1,
"request": "c-r-id=16739&c-t-id=76674",
"Candidate": {
"token": "c-t-id",
"id": "76674",
"Candidate": "BUTLER, MACK N"
},
"Candidate_Entity": {
"token": "c-t-eid",
"id": "15881718",
"Candidate_Entity": "BUTLER, MACK N"
},
"Specific_Party": {
"token": "c-t-pt",
"id": "139",
"Specific_Party": "REPUBLICAN"
},
"General_Party": {
"token": "c-t-p",
"id": "2",
"General_Party": "Republican"
},
"Election_Jurisdiction": {
"token": "s",
"id": "AL",
"Election_Jurisdiction": "AL"
},
"Election_Year": {
"token": "y",
"id": "2012",
"Election_Year": "2012"
},
"Election_Type": {
"token": "c-r-t",
"id": "3",
"Election_Type": "Special"
},
"Office_Sought": {
"token": "c-r-osid",
"id": "143",
"Office_Sought": "HOUSE DISTRICT 030"
},
"Election_Status": {
"token": "c-t-ftsts",
"id": "Won-General",
"Election_Status": "Won-General"
},
"Incumbency_Status": {
"token": "c-t-ico",
"id": "O",
"Incumbency_Status": "Open"
},
"#_of_Records": {
"#_of_Records": "197"
},
"Total_$": {
"Total_$": "94700.08"
}
},
{
"record_id": 2,
"request": "c-r-id=16739&c-t-id=76438",
"Candidate": {
"token": "c-t-id",
"id": "76438",
"Candidate": "MCGLAUGHN, BETH"
},
"Candidate_Entity": {
"token": "c-t-eid",
"id": "15881720",
"Candidate_Entity": "MCGLAUGHN, BETH"
},
"Specific_Party": {
"token": "c-t-pt",
"id": "33",
"Specific_Party": "DEMOCRATIC"
},
"General_Party": {
"token": "c-t-p",
"id": "1",
"General_Party": "Democratic"
},
"Election_Jurisdiction": {
"token": "s",
"id": "AL",
"Election_Jurisdiction": "AL"
},
"Election_Year": {
"token": "y",
"id": "2012",
"Election_Year": "2012"
},
"Election_Type": {
"token": "c-r-t",
"id": "3",
"Election_Type": "Special"
},
"Office_Sought": {
"token": "c-r-osid",
"id": "143",
"Office_Sought": "HOUSE DISTRICT 030"
},
"Election_Status": {
"token": "c-t-ftsts",
"id": "Lost-General",
"Election_Status": "Lost-General"
},
"Incumbency_Status": {
"token": "c-t-ico",
"id": "O",
"Incumbency_Status": "Open"
},
"#_of_Records": {
"#_of_Records": "39"
},
"Total_$": {
"Total_$": "22537.65"
}
},
{
"record_id": 3,
"request": "c-r-id=16739&c-t-id=28927",
"Candidate": {
"token": "c-t-id",
"id": "28927",
"Candidate": "MCHUGH, ROB"
},
"Candidate_Entity": {
"token": "c-t-eid",
"id": "15881719",
"Candidate_Entity": "MCHUGH, ROB"
},
"Specific_Party": {
"token": "c-t-pt",
"id": "139",
"Specific_Party": "REPUBLICAN"
},
"General_Party": {
"token": "c-t-p",
"id": "2",
"General_Party": "Republican"
},
"Election_Jurisdiction": {
"token": "s",
"id": "AL",
"Election_Jurisdiction": "AL"
},
"Election_Year": {
"token": "y",
"id": "2012",
"Election_Year": "2012"
},
"Election_Type": {
"token": "c-r-t",
"id": "3",
"Election_Type": "Special"
},
"Office_Sought": {
"token": "c-r-osid",
"id": "143",
"Office_Sought": "HOUSE DISTRICT 030"
},
"Election_Status": {
"token": "c-t-ftsts",
"id": "Lost-Primary",
"Election_Status": "Lost-Primary"
},
"Incumbency_Status": {
"token": "c-t-ico",
"id": "O",
"Incumbency_Status": "Open"
},
"#_of_Records": {
"#_of_Records": "0"
},
"Total_$": {
"Total_$": "0.00"
}
}
]
}

remove unnecessary hierarchy from json output

I am building an admin backend for an android app. My code provides a json output which the android developer then uses in his app. The developer asked me if it is possible to reduce the hierarchy level in the json output
as in remove the highlighted []0 and put the contents directly inside the []data instead.
This is my current php code
if($type == 1 ) //Handle item display
{
try
{
$query = "SELECT category FROM category";
$result= $DBH->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
$cat = $row['category'];
$query1 = "SELECT * FROM item WHERE catagory='$cat'";
$value = $DBH->query($query1);
if($row1 = $value->fetchAll(PDO::FETCH_OBJ)){
$main[] = array('data'=>array($row1));
}
else
{
$main[] = array('data'=>array('catagory'=>$row['category']));
}
}
echo json_encode($main);
$result->closeCursor(); //Close database connection free resources
$DBH = null;
}
catch(PDOException $e){
print $e->getMessage ();
die();
}
}
And the json output being generated
[
{
"data": [
[
{
"id": "2",
"name": "rice",
"price": "20",
"description": "Plain Rice",
"image": "4106_rice.jpg",
"time": "12 mins",
"catagory": "Lunch",
"subcat": ""
},
{
"id": "3",
"name": "item 1",
"price": "32",
"description": "item 1 description",
"image": "1370_2Ckjikljklkljh.jpg",
"time": "10",
"catagory": "Lunch",
"subcat": "Chicken Soup"
},
{
"id": "4",
"name": "hello",
"price": "10",
"description": "fgsdjfsfsdj",
"image": "",
"time": "76",
"catagory": "Lunch",
"subcat": ""
}
]
]
},
{
"data": {
"catagory": "Dinner"
}
},
{
"data": {
"catagory": "Soup"
}
},
{
"data": {
"catagory": "Test"
}
}
]
I am not very sure if I can make the changes he asked or if it is possible. Is it doable?
Your json structure is inconsistent and try this approach, will be easier for the developer to parse
{
"response": [
{
"data": [
{
"id": "2",
"name": "rice",
"price": "20",
"description": "Plain Rice",
"image": "4106_rice.jpg",
"time": "12 mins",
"catagory": "Lunch",
"subcat": ""
},
{
"id": "3",
"name": "item 1",
"price": "32",
"description": "item 1 description",
"image": "1370_2Ckjikljklkljh.jpg",
"time": "10",
"catagory": "Lunch",
"subcat": "Chicken Soup"
},
{
"id": "4",
"name": "hello",
"price": "10",
"description": "fgsdjfsfsdj",
"image": "",
"time": "76",
"catagory": "Lunch",
"subcat": ""
}
]
},
{
"data": [
{
"catagory": "Dinner"
}
]
},
{
"data": [
{
"catagory": "Soup"
}
]
},
{
"data": [
{
"catagory": "Test"
}
]
}
]
}

How to access the JSON's multi-level objects with jQuery [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 9 years ago.
In CodeIgniter, in PHP to create a nested-like elements for dropdown <select> I'am using this function:
function list_categories(&$result, $cats, $sub = ''){ // <- THIS
foreach($cats as $cat){
//$cat['category']->id = $sub.$cat['category']->title;
$result[$cat['category']->id] = $sub.$cat['category']->title; // <- THIS
if( sizeof($cat['children']) > 0 ){
$sub2 = str_replace('—→ ', '–', $sub);
$sub2.= '–→ ';
list_categories($result, $cat['children'], $sub2); // <- THIS
}
}
}
// Make an array available outside the function
$categoryData = array(0 => '-- '.lang('FORM_SELECT_CATTOP').' --');
// Launch the function to fill out the array with nested sets
list_categories($categoryData, $categories);
Which generates the HTML <select> list:
I want to do the same from retrieved JSON in jQuery but can't find the answer to go deeper than first level of JSON objects with this jQuery function:
$.getJSON('../raw_get_categories/'+com_id_selected+'/0', function(data){
var items = [];
$.each(data, function(key, value, sub){
items.push('<option id="'+ key[0] + '">' + value[0] + '</option>');
});
console.log(items);
});
And this is the JSON I want to manage and retrieve the same values from it like in PHP code:
{
"28": {
"category": {
"id": "28", // <<< I need to retrieve THIS
"pid": "0",
"com_id": "2",
"route_id": "59",
"excerpt": "",
"ordering": "1",
"title": "Oblecenie a vybava",
"slug": "oblecenie-a-vybava1",
"description": "",
"image": "clothes.png",
"seo_title": "",
"meta": ""
},
"compname": {
"id": "2",
"name": "E-commerce"
},
"children": {
"61": {
"category": {
"id": "61", // <<< I need to retrieve THIS
"pid": "28",
"com_id": "2",
"route_id": "52",
"excerpt": "",
"ordering": "1",
"title": "Ubor na hlavu",
"slug": "ubor-na-hlavu1",
"description": "<p>Capice, Klobuky, Panamy, Baretky, Prilby, Kukly<br></p>",
"image": "clothes-head.png",
"seo_title": "",
"meta": ""
},
"compname": {
"id": "2",
"name": "E-commerce"
},
"children": [ ]
},
"30": {
"category": {
"id": "30",
"pid": "28",
"com_id": "2",
"route_id": "53",
"excerpt": "",
"ordering": "2",
"title": "Bundy a vetrovky",
"slug": "bundy-a-vetrovky",
"description": "",
"image": "",
"seo_title": "",
"meta": ""
},
"compname": {
"id": "2",
"name": "E-commerce"
},
"children": {
"34": {
"category": {
"id": "34",
"pid": "30",
"com_id": "2",
"route_id": "0",
"excerpt": "",
"ordering": "0",
"title": "Letne",
"slug": "letne",
"description": "",
"image": "",
"seo_title": "",
"meta": ""
},
"compname": {
"id": "2",
"name": "E-commerce"
},
"children": [ ]
},
"35": {
"category": {
"id": "35",
"pid": "30",
"com_id": "2",
"route_id": "0",
"excerpt": "",
"ordering": "0",
"title": "Vsesezonne",
"slug": "vsesezonne",
"description": "",
"image": "",
"seo_title": "",
"meta": ""
},
"compname": {
"id": "2",
"name": "E-commerce"
},
"children": [ ]
},
"33": {
"category": {
"id": "33",
"pid": "30",
"com_id": "2",
"route_id": "0",
"excerpt": "",
"ordering": "0",
"title": "Zimne",
"slug": "zimne",
"description": "",
"image": "",
"seo_title": "",
"meta": ""
},
"compname": {
"id": "2",
"name": "E-commerce"
},
"children": [ ]
}
}
},
"31": {
"category": {
"id": "31",
"pid": "28",
"com_id": "2",
"route_id": "54",
"excerpt": "",
"ordering": "3",
"title": "Nohavice a teplaky",
"slug": "nohavice-a-teplaky",
"description": "",
"image": "",
"seo_title": "",
"meta": ""
},
"compname": {
"id": "2",
"name": "E-commerce"
},
"children": [ ]
},
"32": {
"category": {
"id": "32",
"pid": "28",
"com_id": "2",
"route_id": "55",
"excerpt": "",
"ordering": "4",
"title": "Obuv",
"slug": "obuv",
"description": "",
"image": "",
"seo_title": "",
"meta": ""
},
"compname": {
"id": "2",
"name": "E-commerce"
},
"children": [ ]
}
}
},
"38": {
...
}
Could someone suggest me the appropriate way to achieve the same foreach statement in jQuery pls?
Juste use point to get more childs
$.getJSON('filename.php', function(data) {
$('#List li').remove();
$.each(data, function(index, item) {
$('#list').append('<li>'+item.category.id+'</li>');
});
});
You can do something like this:
$.each(data.actions, function(entryIndex, entry) {
var html = '<li class="top-level">' + this.action + '</li>';
});
Source

Categories