Date json Object json in angularjs - javascript

I have json result which contain set of json objects.I could not get json object because json object is in integer value.Here is my json result
[{
"serverdatetime": "2016-09-23 12:21:31",
"game_result_array": {
"2016-09-23": [{
"eShowOnHome": "Yes",
"dModifiedDate": "2016-09-22",
"eText": "No",
"eTodayGame": "No",
"eDelay": "No",
"eInvert": "None",
"eResultOrder": "No",
"iHGameID": "56444",
"iGameID": "120",
"vGameTitle": "Gana M\u00e1s",
"eStats": "Yes",
"vUrl": "gana-mas-loteria-nacional",
"vGameLogo": "https:\/\/s3.amazonaws.com\/cdn.kiskooloterias.com\/dominicanas\/upload\/game_logo\/120\/loteria-nacional-dominicana.jpg",
"companymodifieddate": "2011-12-19 13:35:54",
"vCompanyLogo": "https:\/\/s3.amazonaws.com\/cdn.kiskooloterias.com\/dominicanas\/upload\/company\/76\/1373805675_loteria-nacional.jpg",
"gamemodifieddate": "2016-01-05",
"iCompanyID": "76",
"vCompanyName": "Loter\u00eda Nacional",
"vCompanyurl": "loteria-nacional-resultados",
"dLastLotteryDate": "2016-09-22",
"tScore": "28 01 96"
}]
},
"company_ids": "75,76,77,78,84",
"game_ids": "93,94,95,96,98,127,92,111,120,131,100,101,102,114,117,108,171,172",
"success": "1",
"message": "Record found"
}]
Here is the code what i tried
$http({
url : baseUrl,
method :'Post',
data : param
})
.success(function (result) {
$scope.rank =result.game_result_array["2016-09-23"].eShowOnHome;
}
Is there anyway to get json objects? help me. Thanks in advance

game_result_array is an array, so you need to specify the index.
This should work fine.
$scope.rank =result.game_result_array["2016-09-23"][0].eShowOnHome;

You could cast variable that are meant to be integer, Because When Calling From The endpoint, the json with integer types will be shown as strings.
example below shows how you do that using laravel/lumen
$x = Data::all();
return (int)$x->price;
hope you get the idea

Related

JSON getting object inside a JSON

I am trying to get an object from inside a JSON but I can't. It only gives me undefined.
But when I check the result on the console it gives me the right results.
Here is my JSON
{
users: [
{
userID: "151",
userFirstname: "first",
userMiddlename: "middle",
userLastname: "latname",
userAddress: "qewasd",
userContactNumber: "123456",
userRole: "role",
userName: "user",
userPassword: "pass",
userEmail: "test#gmail.com",
userPitch: "Very good",
userExperience: "5",
userFirm: "Sample",
userRollNo: "0"
}
]
}
and here is my javascript
$(document).ready(function () {
$.getJSON('http://batz.web/Sandbox/details.php?userID=151', function (results){
document.getElementById("title").innerHTML = results.userID;
console.log(results);
});
});
Ok look at your json, userID is not a direct child of the results object, which means It will always return null every time you try to get the value of undefined field
You first need to get the array's content with the key(left side of full colon), as the array is in "users" field(or key) ,userId is not still in the array's field, so you gotta point with an index(e.g,0,1,2,...) to get the object which contain userID
...
document.getElementById("title").innerHTML = results.users[0].userId;
...
Here is the fiddle

Parsing Non Standard JSON in Angular Js

I am getting a JSON response from a Restful service in the following format,
{
"comments":{
"columns":[
"clientId",
"treatmentDate",
"comments",
"photo",
"practitioner"
],
"records":[
[
"1",
"2016-09-12",
"Some Coments",
"0",
"Doc 4"
],
[
"1",
"2016-09-11",
"DDD oNE",
"1",
"Docc 3"
]
]
}
}
Record is starting with table name and separate arrays of columns and records follows. Angular is not accepting data is this format. However if I provide data with standard format as follows, it works perfectly.
[
{
"clientId":"1",
"treatmentDate":"2016-09-12",
"comments":"Some Coments",
"photo":"0",
"practitioner":"Doc 4"
},
{
"clientId":"1",
"treatmentDate":"2016-09-11",
"comments":"DDD oNE",
"photo":"1",
"practitioner":"Docc 3"
}
]
Is there a directive that can do this for me or shall I create a custom function, any ideas?
Is there a reason you cannot just manually reshape the data to conform the form you expect?
var data = json.comments.records.map(function(record) {
return json.comments.columns.reduce(function(reshaped, columnName, idx) {
reshaped[columnName] = record[idx];
return reshaped;
}, {});
});
Be careful with this though; this expects the length of each of the arrays in records to always be the same as the number of column names.

Return JSON results as JS array with AJAX?

Apologies in advance - I am new to this and so other answers have not been able to help me.
I have used AJAX to send data to a PHP script (part of a 3rd party API). The PHP script returns the results as JSON, but I have no idea how to format these on my HTML page.
Ultimately, I would like to save the JSON results as an array and then use JS/Jquery to format them on the page.
I am not sure how to modify the PHP and AJAX scripts to achieve this. Can anyone point me in the right direction?
My AJAX:
$.ajax({
type: 'POST',
url: 'calculator.php',
data: {toPostcode: toPostcodeValue, parcelLengthInCMs: parcelLengthInCMsValue, parcelHeighthInCMs: parcelHeighthInCMsValue, parcelWidthInCMs: parcelWidthInCMsValue, parcelWeightInKGs: parcelWeightInKGsValue},
success: function(data) {
<!--NOT SURE WHAT TO PUT HERE-->
}
})
PHP (after the calculator does its thing - not sure if it needs to be changed):
$serviceTypesJSON = json_decode($rawBody);
echo json_encode($serviceTypesJSON);
The expected JSON results should look like:
{
"services": {
"service" : [
{
"code": "AUS_PARCEL_REGULAR",
"name": "Parcel Post (your own packaging)",
"speed": 2,
"price": 6.95,
"max_extra_cover": 5000,
"extra_cover_rule": "100,1.5,1.5",
"icon_url": "http://test-static.npe.auspost.com.au/api/images/pac/regular_post_box.png",
"description": "Based on the size and weight you've entered",
"details": "Check our ",
"delivery_time": "Delivered in up to 3 business days",
"ui_display_order": 1,
"options": {
"option": [
{
"code": "AUS_SERVICE_OPTION_STANDARD",
"name": "Standard Service",
"price": "0.00",
"price_type": "static",
"option_type": "optional",
"ui_display_order": 1
},
{
"code": "AUS_SERVICE_OPTION_SIGNATURE_ON_DELIVERY",
"name": "Signature on Delivery",
"price": 2.95,
"price_type": "static",
"option_type": "optional",
"tooltip": "Signature on Delivery provides you with the peace of mind that your item has been delivered and signed for.",
"ui_display_order": 2,
"suboptions": {
"option": {
"code": "AUS_SERVICE_OPTION_EXTRA_COVER",
"name": "Extra Cover",
"option_type": "optional",
"price_type": "dynamic",
"tooltip": "Extra Cover provides cover for loss, damage or theft of your item and will fully compensate you to the value specified for your item.",
"ui_display_order": 1
}
}
}
]
}
},
You can do two things, if the return data is JSON use dataType: "json" in the AJAX call.
Edit 1
If you are using dataType: "json". Which is more preferred if you are sure the data return is JSON string. data variable in the success will directly give you the JSON object. I think you can access it like data['services'].
success: function (data) {
jsonObj = $.parseJSON(data);
//this gives you the inner onject of the return data
servicesObj = jsonObj.services;
}
Or you can just get the data then use jQuery.parseJSON() to parse the data string into JSON object.
$.ajax({
type: 'POST',
url: 'calculator.php',
data: {
toPostcode: toPostcodeValue,
parcelLengthInCMs: parcelLengthInCMsValue,
parcelHeighthInCMs: parcelHeighthInCMsValue,
parcelWidthInCMs: parcelWidthInCMsValue,
parcelWeightInKGs: parcelWeightInKGsValue
},
success: function (data) {
jsonObj = $.parseJSON(data);
//this gives you the inner onject of the return data
servicesObj = jsonObj.services; //or jsonObj["services"]
}
})
Your success function will never be called if you are using
echo json_encode(); in your php script.
You should add dataType:'json' after type:'POST' and then your success function will get called and will get the result returned by server in data

display json data using xhrget (DOJO)

I am unable to figure out what is the problem with displaying json data..below is the code
var xhrGet1 = dojo.xhrGet({
url: "Page/",
handleAs: "json",
handle: function(response)
{
dojo.byId('json-data').innerHTML = response.questions[0];
}
});
Html
<div id='json-data'></div>
And my json file looks like this
{
"Info": {
"PURPOSE": ".... ",
},
"questions": [
{
"ID": 1,
"Question": "User ID",
"Information": "",
}, {
"ID": 2,
"Question": "Name",
"Information": "",
}
],
so on...any ideas??
The property handleAs : "json" in your xhr call makes the incoming json automatically eval'ed to javascript objects. So, you have to convert your javascript object back to string using JSON.stringify.
e.g. :
dojo.byId('json-data').innerHTML = JSON.stringify(response.questions[0]);
You can also use dojo.toJson for the same purpose. It uses json.stringify but has the benefit of having a second argument ("prettyprint"), allowing you to pretty-print out of the box, like this :
dojo.byId('json-data').innerHTML = dojo.toJson(response.questions[0], true);
wrap your JSON with PRE and CODE tags.
So:
dojo.byId('json-data').innerHTML = "<pre>code>" + response.questions[0] + "</code></pre>";
Also see: Display JSON as HTML for some libraries that can help you pretty-format your JSON when rendering in the browser

How to access JSON element which has "-" character in the name in JavaScript

I have a JSON object which returns following values.
{
"articles":[
{
"paper-id":"id",
"paper-id-type":"type",
"title":"title",
"url":"url",
"abstract":"abs",
"date":"date",
"publication-forum":"forum",
"publication-forum-type":"type",
"authors":"auth",
"keywords":"key1,key2"
}
}
I tried to access these results through JavaScript.
First I created an array and assigned these results to the array.
The content of the array (named articles) object looks like this;
abstract: "xxx"
authors: "yyy"
date: "1111"
keywords: "key1, key2"
paper-id: "abc"
paper-id-type: "xxx"
publication-forum: "yyy"
publication-forum-type: "zzz"
title: "www"
url: "url"
Then I tried to access each value in these elements using the format,
articles[0]["abstract"]
It works for elements that do not have "-" character. So when I tried to extract the paper-id;
articles[0]["paper-id"]
I'm getting the error [Exception: SyntaxError: Unexpected token []
Does anyone know how to solve this problem ?
The problem is because you forgot to close the [] and the {} in your JSON
You JSON should look like this
{
"articles":[
{
"paper-id":"id",
"paper-id-type":"type",
"title":"title",
"url":"url",
"abstract":"abs",
"date":"date",
"publication-forum":"forum",
"publication-forum-type":"type",
"authors":"auth",
"keywords":"key1,key2"
}]
}
abc = {
"articles": [{
"paper-id": "id",
"paper-id-type": "type",
"title": "title",
"url": "url",
"abstract": "abs",
"date": "date",
"publication-forum": "forum",
"publication-forum-type": "type",
"authors": "auth",
"keywords": "key1,key2"
}
]
};
for (i in abc['articles'][0]) {
console.log(abc['articles'][0][i]);
}

Categories