JSON can't be parsed using Javascript - javascript

I have the following JSON reply from a PHP file:
[
{
"color": "black",
"product_name": "Prod2",
"revision": "apps/"
},
{
"color": "green",
"product_name": "Prod1",
"revision": "dev/"
}
]
(tested OK on JSONLint)
And Javascript:
$(document).ready(function(){
$('.target').keyup(function() {
var package_name = "name";
var package_version = "version";
var filter_results = "filter";
$.post('includes/package_filter.php', { package_name: package_name, package_version: package_version, filter_results: filter_results }, function(return_result) {
obj = JSON.parse(return_result);
alert(obj.product_name);
var existingDiv = document.getElementById('other');
existingDiv.innerHTML = CreateTable(return_result);
});
});
});
The return_result doesn't seem to be correct since I get Error: SyntaxError: JSON.parse: unexpected end of data when doing the JSON.parse
I also don't go further to the alrt...
What could be wrong?
My PHP file is similar to:
<?php
function package_filter($package_name, $package_version, $filter_results){
foreach ($descriptions as $descriptions_display) {
...
$array_to_return[] = array('color' => $color , 'product_name' => $descriptions_display['product_name'] , 'revision' => $descriptions_display['revision']);
}
return json_encode($array_to_return);
}
?>
My goal is to create a table with my CreateTable function but there is something wrong before.

When dealing with JSON just set fourth parameter in post() method to json:
$.post('includes/package_filter.php', { /* params */ }, function(return_result) {
// return_result[0].product_name;
}, 'json');

Check the encoding of the response UTF-8 ASCII you may have Characters that are messing up with the parser.

Related

Uncaught (in promise) error when trying to check a json response in an if statement

I have data as a JSON object, and want to push elements of data into jsonArray, if the id inside the data JSON object matches that of the buttonId. Then I want to send to a modal's innerHTML for display.
data gets the response:
[{"id":"4","task_detail":"Use online reports to gather data, confirm with manager and push client data back to Github."},{"id":"6","task_detail":"Pull client data, analyse and push back"},{"id":"9","task_detail":"Perms and user roles in db need creating"},{"id":"10","task_detail":"Pull expense data into API JSON the graph with AJAX and Chart JS"},{"id":"11","task_detail":"Left Side Navigation, requires BS and CSS Style"},{"id":"12","task_detail":"CSS Pipeline color scheme"},{"id":"13","task_detail":"Pull from db and display"},{"id":"14","task_detail":"Export to Excel for tables in reports"},{"id":"15","task_detail":"Test and come up with report data\/ideas to complete"},{"id":"16","task_detail":"Sort by status and date created"},{"id":"17","task_detail":"Add date created to the pipeline table"},{"id":"18","task_detail":"Display info"},{"id":"19","task_detail":"Add option for user to change details - password"},{"id":"20","task_detail":"Collapse from Bootstrap"},{"id":"21","task_detail":"After complete with 1, mimic to 2-5, update project.php buttons"},{"id":"22","task_detail":"Use alert or modal viewer to check if user if sure to delete, once btn pressed"}]
ERROR: 409 Uncaught (in promise) TypeError: Cannot read property 'id' of undefined
at handleJsonData
for line if (arrData[i].id == buttonId) {
const pipe_api_url = 'http://localhost/site/handler.php';
var buttonId;
var taskDetail;
var jsonArray = [];
const data = [];
var stringData = [];
async function handleJsonData() {
const response = await fetch(pipe_api_url);
const data = await response.json();
var stringData = JSON.stringify(data);
console.log("Data: "+data);
console.log("stringData: "+stringData);
var hrefurl = window.location.href;
console.log("handleJsonData hrefurl: "+hrefurl);
var btnIndex = hrefurl.indexOf("btnId=");
console.log("handleJsonData btnIndex: "+btnIndex); //index 49 at currently
var startOfurlSlice = btnIndex + 6;
var endOfUrlSlice = btnIndex.length;
var slicedHrefUrl = hrefurl.slice(startOfurlSlice, endOfUrlSlice);
console.log("handleJsonData slicedHrefUrl: "+slicedHrefUrl);
var buttonId = slicedHrefUrl;
for(i = 0; i <= buttonId; i++) {
if (data[i].id == buttonId) {
jsonArray = [];
//jsonArray.push(data[i].id);
jsonArray.push(data[i].task_detail);
console.log("handleJsonData jsonArray "+jsonArray);
}
}
document.getElementById("show-task-details").innerHTML = jsonArray;
}
$("button").click(async function() {
buttonId = this.id; // or alert($(this).attr('id'));
console.log("getBtnId: "+buttonId);
window.location.href = "http://localhost/site/handler.php?btnId=" + buttonId;
document.getElementById("modalLabelPipeDetail").innerHTML = "Details #" + buttonId;
handleJsonData();
});
Here is working code for you.
The reason your data[i].id is getting undefined is that you are not looping through your data response array
I have recreated some HTML and added your response = data statically defined to recreate the working code.
You can see i am doing forEach() on the data and checking if buttonId is mataching with the data.id
It adding the task_details to the jsonArray four time i am not sure why you looping through the button.length as well so i will leave that one for you.
Working Demo: https://jsfiddle.net/usmanmunir/eros9puf/31/
Run snippet below to see it working
const pipe_api_url = 'http://localhost/site/handler.php';
var buttonId;
var taskDetail;
var jsonArray = [];
const data = [];
var stringData = [];
async function handleJsonData() {
//const response = await fetch(pipe_api_url);
const data = [{
"id": "4",
"task_detail": "Use online reports to gather data, confirm with manager and push client data back to Github."
}, {
"id": "6",
"task_detail": "Pull client data, analyse and push back"
}, {
"id": "9",
"task_detail": "Perms and user roles in db need creating"
}, {
"id": "10",
"task_detail": "Pull expense data into API JSON the graph with AJAX and Chart JS"
}, {
"id": "11",
"task_detail": "Left Side Navigation, requires BS and CSS Style"
}, {
"id": "12",
"task_detail": "CSS Pipeline color scheme"
}, {
"id": "13",
"task_detail": "Pull from db and display"
}, {
"id": "14",
"task_detail": "Export to Excel for tables in reports"
}, {
"id": "15",
"task_detail": "Test and come up with report data\/ideas to complete"
}, {
"id": "16",
"task_detail": "Sort by status and date created"
}, {
"id": "17",
"task_detail": "Add date created to the pipeline table"
}, {
"id": "18",
"task_detail": "Display info"
}, {
"id": "19",
"task_detail": "Add option for user to change details - password"
}, {
"id": "20",
"task_detail": "Collapse from Bootstrap"
}, {
"id": "21",
"task_detail": "After complete with 1, mimic to 2-5, update project.php buttons"
}, {
"id": "22",
"task_detail": "Use alert or modal viewer to check if user if sure to delete, once btn pressed"
}]
var stringData = JSON.stringify(data);
//console.log("Data: "+data);
//console.log("stringData: "+stringData);
var hrefurl = window.location.href;
//console.log("handleJsonData hrefurl: "+hrefurl);
var btnIndex = hrefurl.indexOf("btnId=1");
//console.log("handleJsonData btnIndex: "+btnIndex); //index 49 at currently
var startOfurlSlice = btnIndex + 6;
var endOfUrlSlice = btnIndex.length;
var slicedHrefUrl = hrefurl.slice(startOfurlSlice, endOfUrlSlice);
//console.log("handleJsonData slicedHrefUrl: "+slicedHrefUrl);
//var buttonId = slicedHrefUrl;
var buttonId = 4;
for (i = 0; i <= buttonId; i++) {
data.forEach(function(data) {
if (data.id == buttonId) {
//jsonArray.push(data[0].id);
jsonArray.push(data.task_detail);
//console.log("handleJsonData jsonArray " + jsonArray);
}
})
}
document.getElementById("show-task-details").innerHTML = jsonArray;
}
$("button").click(async function() {
buttonId = this.id; // or alert($(this).attr('id'));
//window.location.href = "http://localhost/site/handler.php?btnId=" + buttonId;
document.getElementById("modalLabelPipeDetail").innerHTML = "Details #" + buttonId;
handleJsonData();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="4">Click ME - ID = 4</button>
<div id="modalLabelPipeDetail"></div>
<div id="show-task-details"></div>

access object in parsed nested JSON in Google Apps Script

I am trying to access the student tags array which has an object inside of it (student_tags:tag:"do not contact") Can someone please help me with the syntax on getting this data? I am pretty sure my syntax in retrieving this array is incorrect.
JSON Data being fetched:
{
"id":"e90c4c93-207c-49f7-89c4-eb85b3315dd5",
"created_by_user_id":"8560ed12-2858-4237-bea2-3dcab82637d3",
"date_created":"2019-08-06T22:54:59.583257+00:00",
"person_number":5973,
"first_name":"Test",
"middle_name":"James",
"last_name":"Cook",
"birth_name":null,
"email":"test#gmail.com",
"alt_email":null,
"facebook_url":null,
"linkedin_url":"https://www.linkedin.com/in/test-burns-273a5165/",
"gender":"Male",
"phone_numbers":[
{
"phone_type":"Mobile",
"number":"449288809"
},
{
"phone_type":"Home",
"number":"93938289"
}
],
"is_no_contact":false,
"is_client":false,
"student_detail":{
"onboarding_student_setting_id":"e189187a-cc91-43c6-ac44-635328b1e95a",
"student_onboarding_setting":{
"id":"e189187a-cc91-43c6-ac44-635328b1e95a",
"created_by_user_id":"562a63a2-e24e-4ff7-8358-dfb74ed6c70a",
"title":"High School On-boarding Process",
"description":"High School On-boarding Process",
"is_default":false,
"onboarding_steps":[
{
"step_id":"9cd30560-1c3c-4382-b8a2-505e78b9ce4d",
"set_tags":[
"Student Tag"
],
"set_to_status":"Potential",
"title":"Contact",
"short_title":"Contact",
"is_attachment_required":null
},
{
"step_id":"e6f90546-a516-416c-a880-9adc10358f1d",
"set_tags":[
],
"set_to_status":"Pipeline",
"title":"Program Orientation",
"short_title":"PO",
"is_attachment_required":null
},
{
"step_id":"8660df59-ddd8-4182-b6ca-c44e3de70969",
"set_tags":[
],
"set_to_status":"Confirmed",
"title":"Parental Consent",
"short_title":"Parental Consent",
"is_attachment_required":true
}
],
"is_disabled":false
},
"student_onboarding_history":[
],
"onboarding_steps_complete":null,
"onboarding_percent":null,
"graduating_student_setting_id":null,
"student_graduating_setting":null,
"student_graduating_history":[
],
"graduating_steps_complete":null,
"graduating_percent":null,
"is_active":true,
"date_deactivated":"2019-08-09T03:36:57.977584",
"deactivated_person_id":"562a63a2-e24e-4ff7-8358-dfb74ed6c70a",
"deactviated_notes":null,
"student_status":"Pipeline",
"language_group":null,
"heritage":null,
"date_ics_set":"2019-08-08T04:28:48.832170",
"ics_by_person_id":"562a63a2-e24e-4ff7-8358-dfb74ed6c70a",
"ics_status":"Active",
"ics_id":null,
"ics_start":null,
"ics_end":null,
"ics_notes":null,
"student_tags":[
{
"tag":"Do not contact",
"date_added":"2019-08-13 06:06:13.012817"
}
],
"student_source":"Other",
"date_of_birth":"2019-08-07",
"semester_number_start":null,
"semester_year_start":null,
"semester_number_end":null,
"semester_year_end":null,
"location_address":{
"line_1":"34 Adelaide Avenue",
"line_2":"",
"suburb":"east lindfield",
"postcode":"2322",
"state":"",
"country_code":"AU",
"location_description":"east lindfield, ",
"formatted_location":null,
"latitude":"-33.7691871",
"longitude":"151.1863407"
},
"emergency_first_name":"Someone",
"emergency_last_name":"",
"emergency_phone_numbers":[
],
"emergency_address":{
"line_1":"hi",
"line_2":"",
"suburb":"willoughby",
"postcode":"4154",
"state":"NSW",
"country_code":"AU",
"location_description":"willoughby, NSW",
"formatted_location":null,
"latitude":"-33.804179",
"longitude":"151.2042376"
},
"emergency_relationship":"Auntie",
"university":null,
"campus":null,
"degree_pool_id":[
],
"degree":null,
"degree_major":null,
"high_school":"School",
"high_school_complete":null,
"is_travel_required":null,
"date_alumni_set":null,
"alumni_set_by_person_id":null,
"alumni_company":null,
"alumni_job_title":null,
"alumni_city":null,
"alumni_state":null,
"alumni_country_code":null,
"alumni_notes":null,
"is_at_risk":null,
"date_at_risk_set":null,
"at_risk_by_person_id":null,
"at_risk_context":null,
"at_risk_reasons":null,
"at_risk_semester":null,
"at_risk_year":null,
"at_risk_notes":null,
"quick_notes":null,
"cv_url":null,
"public_summary":null,
"public_profile":null,
"is_graduating":null,
"graduating_by_person_id":null,
"graduating_semester":null,
"graduating_year":null,
"graduating_notes":null,
"advisor_users":[
{
"date_created":"2019-08-06T22:54:59.582970+00:00",
"is_primary":true,
"advisor_person_id":"8560ed12-2858-4237-bea2-3dcab82637d3"
}
]
},
"contact_detail":{
"company_id":null,
"contact_tags":null,
"location_address":{
"line_1":null,
"line_2":null,
"suburb":null,
"postcode":null,
"state":null,
"country_code":null,
"location_description":null,
"formatted_location":null,
"latitude":null,
"longitude":null
},
"job_title":null,
"quick_notes":null,
"is_primary":null,
"is_billing":null,
"is_student_contact":null,
"advisor_users":null
},
"current_placements":null,
"previous_placements":null
}
The function returning the JSON response:
var url = "http://api.com/v1/";
var response = UrlFetchApp.fetch(url, options);
var message = response.getContentText();
var code = response.getResponseCode();
Logger.log(message)
var tags = message["student_tags"][0]
Logger.log(tags)
In response to 'would you know how to use the key/value loop to access the same student tag value ("Do not contact")?', I'm not sure I understand the question, but the below code may be a good place to start. Let me know if I'm way off track...
var tags = message.student_detail.student_tags,
i = 0,
len = tags.length;
for (i; i < len; i++) {
var obj = tags[i];
for (a in obj) {
console.log(a, obj[a])
}
}

Angularjs and jquery.datatable with ui.bootstrap - need to show entries in json using a loop

I need to show the entries of the json in a loop.
I'm new in js and angular, and I don't know how to enter a for in the marked place of the code below.
I need to know to do all the code, this just a test for a larger project.
<?php
$estudent[]=array(
"name" => "luis",
"age" => "10");
$estudent[]=array(
"name" => "maria",
"age" => "12");
$objJson=json_encode($estudent);
?>
//here is the js
<script>
var json=eval(<?php echo $objJson; ?>);
//Angularjs and jquery.datatable with ui.bootstrap and ui.utils
var app=angular.module('formvalid', ['ui.bootstrap','ui.utils']);
app.controller('validationCtrl',function($scope){
$scope.data = [
[ //i need to use a loop for show all the studens
json[0].name,
json[0].age,
],
[ //i need to use a loop for show all the studens
json[1].name,
json[1].age,
],
]
$scope.dataTableOpt = {
//custom datatable options
// or load data through ajax call also
"aLengthMenu": [[10, 50, 100,-1], [10, 50, 100,'All']],
};
});
</script>
In my opinion your JSON is valid, try to change format of JSON for something similar to this :
$scope.data = [{
"name": "json[0].name",
"age": "json[0].age"
},
{
"name": "json[1].name",
"age": "json[1].age"
}
]
Then you can easly console or show it
angular.forEach($scope.data, function (value, index) {
console.log($scope.data[index] + ' ' + index);
});
HTML
<ul ng-repeat="json in data">
<li><b>Name: </b> <p>{{json.name}}</p> <b>Age: </b> <p>{{json.age}}</p></li>
</ul>
plunker: http://plnkr.co/edit/s6ix8aEDz0jR3UeXGL6M?p=preview
For this loop you can use:
$scope.data = [];
angular.forEach(json, (item) => {
// here you can get item.age and item.name
$scope.data.push(item);
});
At the end of this loop your $scope.data will have all students in it

How To Loop and Load Section of JSON to New Array

I am getting some dynamic data from Ajax call in JSON format on
var out;
request.done(function( data ) {
out = data;
console.log(out);
});
which looks like
{
"seq":"1",
"node":"1407",
"edge":"1721",
"cost":"0.00155228618815934",
"st_astext":"MULTILINESTRING((-124.339494 49.3269419000001,-124.3387254 49.3269805,-124.338669 49.3270201,-124.3386158 49.3270832000001,-124.3386343 49.3274121000001,-124.3386975 49.3274896,-124.3390742 49.3276439000001,-124.3394701 49.3277238000001,-124.339726 49.3277574000001,-124.3398638 49.3277496000001,-124.3399475 49.3277140000001,-124.3400263 49.3276270000001,-124.3402516 49.3272857000001,-124.340277 49.3271520000001,-124.3402715 49.3270367000001,-124.3402042 49.3269591000001,-124.3401021 49.3269305000001,-124.339494 49.3269419000001))"
}{
"seq":"2",
"node":"2459",
"edge":"43870",
"cost":"0.0014795249102581",
"st_astext":"MULTILINESTRING((-123.4051866 48.4191865000001,-123.4053714 48.4191387000001,-123.405405 48.4190178000001,-123.4050125 48.4186474000001,-123.4047663 48.4185377000001,-123.4045437 48.4185367000001,-123.4044758 48.4185937,-123.4043546 48.4189586000001,-123.404408 48.4190429000001,-123.4051866 48.4191865000001))"
}{
"seq":"3",
"node":"14962",
"edge":"15633",
"cost":"0.00144452021471863",
"st_astext":"MULTILINESTRING((-124.2005178 48.8657682,-124.2008549 48.8656748000001,-124.2011903 48.8656273,-124.2020436 48.8656722000001,-124.2029403 48.8658963,-124.2033335 48.8659029,-124.2034588 48.8658654000001,-124.2034906 48.8658182,-124.2034447 48.8657724,-124.203297 48.8657185000001,-124.203148 48.8656980000001,-124.2027598 48.865705,-124.20221 48.8655579000001,-124.2017332 48.8654932000001,-124.200973 48.8654362,-124.2006816 48.8654025000001,-124.200004 48.8651794,-124.1997069 48.8650816000001,-124.1995273 48.8650453000001,-124.1992556 48.8650290000001,-124.1988955 48.8649418000001,-124.1987556 48.8649332000001,-124.1986996 48.8649719000001,-124.1986801 48.8650336000001,-124.1986764 48.8650454,-124.1987314 48.8651373000001,-124.1988681 48.8651927000001,-124.1992515 48.8652406000001,-124.1995975 48.8653437,-124.2000068 48.8655325,-124.2005013 48.8657606,-124.2005178 48.8657682))"
}{
"seq":"4",
"node":"13891",
"edge":"13862",
"cost":"0.00076542396749831",
"st_astext":"MULTILINESTRING((-124.4606302 49.3438327000001,-124.4605727 49.3436995000001,-124.4604416 49.3435897000001,-124.4602789 49.3435198000001,-124.4601008 49.3434993000001,-124.4599664 49.3435289000001,-124.4598809 49.3436195,-124.4598941 49.3441714000001,-124.4599637 49.3442309000001,-124.4600623 49.3442440000001,-124.4601711 49.3441961,-124.4606302 49.3438327000001))"
}{
"seq":"5",
"node":"3684",
"edge":"28825",
"cost":"0.00117904724673861",
"st_astext":"MULTILINESTRING((-123.3495787 48.4045938,-123.3496211 48.4041484000001,-123.3493846 48.4033146,-123.3492248 48.4032068000001,-123.3490655 48.4031857000001,-123.3489141 48.4032153000001,-123.3486746 48.4033022,-123.3486286 48.4034498,-123.3494207 48.4043084,-123.3495787 48.4045938))"
}{
"seq":"6",
"node":"12168",
"edge":"11270",
"cost":"0.00109953281896407",
"st_astext":"MULTILINESTRING((-123.4652201 48.4475155000001,-123.4648358 48.4482124,-123.4650847 48.4482788,-123.4654424 48.4475732000001,-123.4652201 48.4475155000001))"
}
now I need to load the "st_astext":"MULTILINESTRING of each seq to arrays of arry like
var paths = [
[
[-124.339494,49.3269419000001],
[-124.3387254,49.3269805],
[-124.338669,49.3270201],
...
],
[
[-123.4051866, 48.4191865000001],
[-123.4053714, 48.4191387000001],
[-123.405405, 48.4190178000001],
....
]
];
To accomplish this, you can strip out the "MULTILINE..." portion of your string, and then split that string on a comma to get each set of coordinates. From there, you can split on the space separating the coordinates, and coerce to a Number. Like so:
var data = [{
"seq":"1",
"node":"1407",
"edge":"1721",
"cost":"0.00155228618815934",
"st_astext":"MULTILINESTRING((-124.339494 49.3269419000001,-124.3387254 49.3269805,-124.338669 49.3270201,-124.3386158 49.3270832000001,-124.3386343 49.3274121000001,-124.3386975 49.3274896,-124.3390742 49.3276439000001,-124.3394701 49.3277238000001,-124.339726 49.3277574000001,-124.3398638 49.3277496000001,-124.3399475 49.3277140000001,-124.3400263 49.3276270000001,-124.3402516 49.3272857000001,-124.340277 49.3271520000001,-124.3402715 49.3270367000001,-124.3402042 49.3269591000001,-124.3401021 49.3269305000001,-124.339494 49.3269419000001))"
},{
"seq":"2",
"node":"2459",
"edge":"43870",
"cost":"0.0014795249102581",
"st_astext":"MULTILINESTRING((-123.4051866 48.4191865000001,-123.4053714 48.4191387000001,-123.405405 48.4190178000001,-123.4050125 48.4186474000001,-123.4047663 48.4185377000001,-123.4045437 48.4185367000001,-123.4044758 48.4185937,-123.4043546 48.4189586000001,-123.404408 48.4190429000001,-123.4051866 48.4191865000001))"
},{
"seq":"3",
"node":"14962",
"edge":"15633",
"cost":"0.00144452021471863",
"st_astext":"MULTILINESTRING((-124.2005178 48.8657682,-124.2008549 48.8656748000001,-124.2011903 48.8656273,-124.2020436 48.8656722000001,-124.2029403 48.8658963,-124.2033335 48.8659029,-124.2034588 48.8658654000001,-124.2034906 48.8658182,-124.2034447 48.8657724,-124.203297 48.8657185000001,-124.203148 48.8656980000001,-124.2027598 48.865705,-124.20221 48.8655579000001,-124.2017332 48.8654932000001,-124.200973 48.8654362,-124.2006816 48.8654025000001,-124.200004 48.8651794,-124.1997069 48.8650816000001,-124.1995273 48.8650453000001,-124.1992556 48.8650290000001,-124.1988955 48.8649418000001,-124.1987556 48.8649332000001,-124.1986996 48.8649719000001,-124.1986801 48.8650336000001,-124.1986764 48.8650454,-124.1987314 48.8651373000001,-124.1988681 48.8651927000001,-124.1992515 48.8652406000001,-124.1995975 48.8653437,-124.2000068 48.8655325,-124.2005013 48.8657606,-124.2005178 48.8657682))"
},{
"seq":"4",
"node":"13891",
"edge":"13862",
"cost":"0.00076542396749831",
"st_astext":"MULTILINESTRING((-124.4606302 49.3438327000001,-124.4605727 49.3436995000001,-124.4604416 49.3435897000001,-124.4602789 49.3435198000001,-124.4601008 49.3434993000001,-124.4599664 49.3435289000001,-124.4598809 49.3436195,-124.4598941 49.3441714000001,-124.4599637 49.3442309000001,-124.4600623 49.3442440000001,-124.4601711 49.3441961,-124.4606302 49.3438327000001))"
},{
"seq":"5",
"node":"3684",
"edge":"28825",
"cost":"0.00117904724673861",
"st_astext":"MULTILINESTRING((-123.3495787 48.4045938,-123.3496211 48.4041484000001,-123.3493846 48.4033146,-123.3492248 48.4032068000001,-123.3490655 48.4031857000001,-123.3489141 48.4032153000001,-123.3486746 48.4033022,-123.3486286 48.4034498,-123.3494207 48.4043084,-123.3495787 48.4045938))"
},{
"seq":"6",
"node":"12168",
"edge":"11270",
"cost":"0.00109953281896407",
"st_astext":"MULTILINESTRING((-123.4652201 48.4475155000001,-123.4648358 48.4482124,-123.4650847 48.4482788,-123.4654424 48.4475732000001,-123.4652201 48.4475155000001))"
}];
var paths = data.map(elem => {
var coordsBegin = elem.st_astext.split("((")[1];
var coords = coordsBegin.split("))")[0];
return coords.split(",").map(coord => coord.split(" ").map(Number));
});
console.log(paths);
Assuming the initial data structure is an array of objects, you can loop through it and generate the desired output with Array.prototype.map
const data = [{
"seq":"1",
"node":"1407",
"edge":"1721",
"cost":"0.00155228618815934",
"st_astext":"MULTILINESTRING((-124.339494 49.3269419000001,-124.3387254 49.3269805,-124.338669 49.3270201,-124.3386158 49.3270832000001,-124.3386343 49.3274121000001,-124.3386975 49.3274896,-124.3390742 49.3276439000001,-124.3394701 49.3277238000001,-124.339726 49.3277574000001,-124.3398638 49.3277496000001,-124.3399475 49.3277140000001,-124.3400263 49.3276270000001,-124.3402516 49.3272857000001,-124.340277 49.3271520000001,-124.3402715 49.3270367000001,-124.3402042 49.3269591000001,-124.3401021 49.3269305000001,-124.339494 49.3269419000001))"
}, {
"seq":"2",
"node":"2459",
"edge":"43870",
"cost":"0.0014795249102581",
"st_astext":"MULTILINESTRING((-123.4051866 48.4191865000001,-123.4053714 48.4191387000001,-123.405405 48.4190178000001,-123.4050125 48.4186474000001,-123.4047663 48.4185377000001,-123.4045437 48.4185367000001,-123.4044758 48.4185937,-123.4043546 48.4189586000001,-123.404408 48.4190429000001,-123.4051866 48.4191865000001))"
}, {
"seq":"3",
"node":"14962",
"edge":"15633",
"cost":"0.00144452021471863",
"st_astext":"MULTILINESTRING((-124.2005178 48.8657682,-124.2008549 48.8656748000001,-124.2011903 48.8656273,-124.2020436 48.8656722000001,-124.2029403 48.8658963,-124.2033335 48.8659029,-124.2034588 48.8658654000001,-124.2034906 48.8658182,-124.2034447 48.8657724,-124.203297 48.8657185000001,-124.203148 48.8656980000001,-124.2027598 48.865705,-124.20221 48.8655579000001,-124.2017332 48.8654932000001,-124.200973 48.8654362,-124.2006816 48.8654025000001,-124.200004 48.8651794,-124.1997069 48.8650816000001,-124.1995273 48.8650453000001,-124.1992556 48.8650290000001,-124.1988955 48.8649418000001,-124.1987556 48.8649332000001,-124.1986996 48.8649719000001,-124.1986801 48.8650336000001,-124.1986764 48.8650454,-124.1987314 48.8651373000001,-124.1988681 48.8651927000001,-124.1992515 48.8652406000001,-124.1995975 48.8653437,-124.2000068 48.8655325,-124.2005013 48.8657606,-124.2005178 48.8657682))"
}, {
"seq":"4",
"node":"13891",
"edge":"13862",
"cost":"0.00076542396749831",
"st_astext":"MULTILINESTRING((-124.4606302 49.3438327000001,-124.4605727 49.3436995000001,-124.4604416 49.3435897000001,-124.4602789 49.3435198000001,-124.4601008 49.3434993000001,-124.4599664 49.3435289000001,-124.4598809 49.3436195,-124.4598941 49.3441714000001,-124.4599637 49.3442309000001,-124.4600623 49.3442440000001,-124.4601711 49.3441961,-124.4606302 49.3438327000001))"
}, {
"seq":"5",
"node":"3684",
"edge":"28825",
"cost":"0.00117904724673861",
"st_astext":"MULTILINESTRING((-123.3495787 48.4045938,-123.3496211 48.4041484000001,-123.3493846 48.4033146,-123.3492248 48.4032068000001,-123.3490655 48.4031857000001,-123.3489141 48.4032153000001,-123.3486746 48.4033022,-123.3486286 48.4034498,-123.3494207 48.4043084,-123.3495787 48.4045938))"
}, {
"seq":"6",
"node":"12168",
"edge":"11270",
"cost":"0.00109953281896407",
"st_astext":"MULTILINESTRING((-123.4652201 48.4475155000001,-123.4648358 48.4482124,-123.4650847 48.4482788,-123.4654424 48.4475732000001,-123.4652201 48.4475155000001))"
}];
var paths = data.map(({st_astext}) => {
const [ _ ,numsStr ] = st_astext.match(/\(\((.*)\)\)/);
const arr = numsStr.split(',').map(pair => pair.split(' ').map(Number))
return arr;
});
console.log(paths);

Why can't I access the data in my JSON?

My PHP is:
if(!empty($_POST)&&($_POST['action']=='edit'))
{
foreach ($_POST['selected'] as $edit_id)
{
$query = "SELECT * FROM grocery WHERE id = $edit_id";
$result = dbQuery($query);
break;
}
$rowArr=array();
$inRow = mysqli_fetch_array($result);
$id = $inRow['id'];
$shop = $inRow['shop'];
$category = $inRow['category'];
$item = $inRow['item'];
$qnty = $inRow['quantity'];
$unit = $inRow['unit'];
$price_based_on = $inRow['price_based_on'];
$mrp = $inRow['MRP'];
$sellers_price = $inRow['sellers_price'];
$last_updated_on = $inRow['last_updated_on'];
array_push($rowArr, array('id' => $id, 'shop' => $shop, 'category' =>$category, 'item' => $item, 'qnty' => $qnty, 'unit' => $unit, 'price_based_on' => $price_based_on, 'mrp' => $mrp, 'sellers_price' => $sellers_price, 'last_updated_on' => $last_updated_on));
echo json_encode(array('rowArr' => $rowArr));
}
The output (JSON) produced by the above script is: (I've ensured this is produced in the Chrome's console)
{
"rowArr": [
{
"id": "30",
"shop": "Subhash",
"category": "Spices",
"item": "Duta Corriander Powder",
"qnty": "50",
"unit": "gm",
"price_based_on": "Packet",
"mrp": "15.00",
"sellers_price": "12.00",
"last_updated_on": "2016-12-03"
}
]
}
My jQuery is:
$('#edit').click(function(){
var data = $("#list :input").serialize();
$.post($("#list").attr('action'), data, function(json)
{
if(json.rowArr.length>0)
console.log("Data Exists");
else
console.log("Empty");
currentRow = json.rowArr[0];
console.log(json.rowArr[0].id);
$("#id").val(currentRow.id);
$("#id_disp").val(currentRow.id);
});
});
Strangely enough, neither Data Exists or Empty is produced by the above loop. And when I try to access the JSON data, json.rowArr[0].id I get the following error:
Uncaught TypeError: Cannot read property 'length' of undefined
Why is this happening? How do I fix it?
You should explicitly tell jQuery that your response has JSON format. You should pass 'json' as fourth argument of $.post, according to docs.
$('#edit').click(function(){
var data = $("#list :input").serialize();
$.post($("#list").attr('action'), data, function(json) {
if(json.rowArr.length>0)
console.log("Data Exists");
else
console.log("Empty");
currentRow = json.rowArr[0];
console.log(json.rowArr[0].id);
$("#id").val(currentRow.id);
$("#id_disp").val(currentRow.id);
}, 'json');
});

Categories

Resources