Angularjs - show values from a server request - json

I got this json data back from the server: {"start":"29-11-2014","end":"31-12-2014","pris":"372.27"}
In my .success i have $scope.paymentInfo = data; then i try to output it in my html view like this
{{ paymentInfo.start }}
but it does not work but if i try {{ paymentInfo }} it shows the json object, what do i have to do, to get the start, end etc. ?
$scope.selectMembership = function(values){
//console.log(values);
centerSettings.getPriceForPeriod(values)
.success(function(data) {
console.log(data);
$scope.paymentInfo = data;
})
.error(function(data) {
console.log('fejl ved hentning af centre');
console.log(data);
});
};

I think you need to deserialize the string to Json object.
Try using $scope.paymentInfo = angular.fromJson(data);

Related

Axios request get value from nested array in Vue

In a .vue file I am trying the get value from an axios get response result which is in a nested array. The code looks like the example below (without a search form for query).
<div class="results" v-if="results">
<p>{{ results }}</p>
<p>{{ result }}</p>
</div>
<script>
import axios from 'axios';
export default {
name: 'search',
data () {
return {
query '',
results: '',
result: ''
}
},
methods: {
getResults(query) {
axios.get('https://apiexample.com/api/search.php?t_id=' + query).then( response => {
this.results = response.data.items;
this.result = response.data.items[0]['1:B'];
});
}
}
}
So for this.results I get something similar to
[{"1:A":10,"1:B":20,"1:C":30,"1:D":40,"1:E":50},
{"1:A":20,"1:B":30,"1:C":40,"1:D":50,"1:E":60},
{"1:A":30,"1:B":40,"1:C":50,"1:D":60,"1:E":70},
{"1:A":40,"1:B":50,"1:C":60,"1:D":70,"1:E":80}]
For this.result I am getting undefined when I am trying to get the value of 20. Probably navigating that type of response incorrectly or perhaps something more specific needs to be added to data() {}?
Any help would be appreciated.
Thanks.
As noted in the comments, response.data.items is a string, not an object. This seems like a flawed API response, with the items unnecessarily encoded as a JSON string within the response.
However, assuming that fixing the problem in the server is not possible, the items can be decoded in the UI:
this.results = JSON.parse(response.data.items);
this.result = this.results[0]['1:B'];

Wrong data format for store loadData method ExtJS

I want to call JSON data as much as the amount of data in the store. Here is the code:
storeASF.each(function(stores) {
var trano = stores.data['arf_no'];
Ext.Ajax.request({
results: 0,
url: '/default/home/getdataforeditasf/data2/'+trano+'/id/'+id,
method:'POST',
success: function(result, request){
var returnData = Ext.util.JSON.decode(result.responseText);
arraydata.push(returnData);
Ext.getCmp('save-list').enable();
Ext.getCmp('cancel-list').enable();
},
failure:function( action){
if(action.failureType == 'server'){
obj = Ext.util.JSON.decode(action.response.responseText);
Ext.Msg.alert('Error!', obj.errors.reason);
}else{
Ext.Msg.alert('Warning!', 'Server is unreachable : ' + action.response.responseText);
}
}
});
id++;
});
storeARF.loadData(arraydata);
StoreASF contains data[arf_no] which will be used as a parameter in Ajax request url. StoreASF could contain more than one set of the object store, so looping is possible. For every called JSON data from request would be put to array data, and after the looping is complete, I save it to storeARF with the loadData method.
The problem is, my data format is wrong since loadData can only read JSON type data. I already try JSON stringify and parse, but couldn't replicate the data format. Any suggestion how to do this? Thank you.
Rather than using Ext.util.Json.decode(), normalize the data in success() method using your own logic. For example:
success: function (response) {
console.log(response);
var myData = [];
Ext.Array.forEach(response.data, function (item) {
myData.push({
name: item.name,
email: item.email,
phone: item.phone
});
});
store.load();
}

Parsing JSON object sent through AJAX in Django

This is my code creating a json file:
$( ".save" ).on("click", function(){
var items=[];
$("tr.data").each(function() {
var item = {
itemCode : $(this).find('td:nth-child(1) span').html(),
itemQuantity : $(this).find('td:nth-child(4) span').html()
};
items.push(item);
});
});
Now the json object looks like:
[{"itemcode":"code1","itemquantity":"quantity1"},{"itemcode":"code2","itemquantity":"quantity2"},...]
My question is how do I parse this data in Django view?
Following is my AJAX function for reference:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ bill_details: JSON.stringify(items),
calltype:'save'},
dataType: "application/json", // datatype being sent
success : function(jsondata) {
//do something
},
error : function() {
//do something
}
});
}());
Since I'm sending multiple AJAX request to the same view, I need the 'calltype' data as well.
Thanks you on your answer!! BTW, I badly need to know this simple stuff, which I'm missing
This is my code snippet for parsing:
if (calltype == 'save'):
response_data = {}
bill_data = json.loads(request.POST.get('bill_details'))
itemcode1=bill_details[0]['itemCode']
#this part is just for checking
response_data['name'] = itemcode1
jsondata = json.dumps(response_data)
return HttpResponse(jsondata)
The error being raised is
string indices must be integers
Request your help
For your reference, this is my POST response (taken from traceback):
bill_details = '[{"itemCode":"sav","itemQuantity":"4"}]'
calltype = 'save'
csrfmiddlewaretoken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
EDITED Django View
This is my edited view:
if (calltype == 'save'):
bill_detail = request.POST.get('bill_details')
response_data = {}
bill_data = json.loads(bill_detail)
itemcode1=bill_data[0]['itemCode']
#this part is just for checking
response_data['name'] = itemcode1
jsondata = json.dumps(response_data)
return HttpResponse(jsondata)
I fail to understand the problem. SO, to solve it, my question: what is the datatype of the return for get call and what should be the input datatype for json.loads. Bcoz the error being shown is json.loads file has to be string type!! (Seriously in limbo)
Error:
the JSON object must be str, not 'NoneType'

JSON returning with "\" (Lambda)

I am using AWS Lambda to get JSON from the open weather api and return it.
Here is my code:
var http = require('http');
exports.handler = function(event, context) {
var url = "http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=b1b15e88fa797225412429c1c50c122a";
http.get(url, function(res) {
// Continuously update stream with data
var body = '';
res.on('data', function(d) {
body += d;
});
res.on('end', function() {
context.succeed(body);
});
res.on('error', function(e) {
context.fail("Got error: " + e.message);
});
});
}
It works and returns the JSON, but it is adding backslashes before every " like so:
"{\"coord\":{\"lon\":145.77,\"lat\":-16.92},\"weather\":[{\"id\":803,\"main\":\"Clouds\",\"description\":\"broken clouds\",\"icon\":\"04d\"}],\"base\":\"cmc stations\",\"main\":{\"temp\":303.15,\"pressure\":1008,\"humidity\":74,\"temp_min\":303.15,\"temp_max\":303.15},\"wind\":{\"speed\":3.1,\"deg\":320},\"clouds\":{\"all\":75},\"dt\":1458518400,\"sys\":{\"type\":1,\"id\":8166,\"message\":0.0025,\"country\":\"AU\",\"sunrise\":1458505258,\"sunset\":1458548812},\"id\":2172797,\"name\":\"Cairns\",\"cod\":200}"
This is stopping my over service using (SwiftJSON) detecting this as valid JSON.
Can anyone tell me how to make the API information come out as correctly formatted JSON?
I tried .replace like so:
res.on('end', function() {
result = body.replace('\\', '');
context.succeed(result);
});
It did not change anything. Still had the same output.
You're posting it as a string.
Try context.succeed(JSON.parse(result))
From the docs
The result provided must be JSON.stringify compatible. If AWS Lambda fails to stringify or encounters another error, an unhandled exception is thrown, with the X-Amz-Function-Error response header set to Unhandled.
http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html
So essentially it's taking your json string as a string and calling JSON.stringify on it...thus escaping all the quotes as you're seeing. Pass the parsed JSON object to succeed and it should not have this issue
In case of Java, just return a JSONObject. Looks like when returning string it is trying to do some transformation and ends up escaping all the quotes.
If using Java, the response can be a user defined object as below
class Handler implements RequestHandler<SQSEvent, CustomObject> {
public CustomObject handleRequest(SQSEvent event, Context context) {
return new CustomObject();
}
}
Sample code can be found here.
Do this on your result: response.json()
You can use:
res.on('end', function() {
context.succeed(body.replace(/\\/g, '') );
To replace \ with nothing..

AngularJS service not consuming JSON correctly with HTTP

I am attempting to make a HTTP request to a WebAPI using a AngularJS service and load a HTML page with two nested ng-repeat's (posts and replies). I can get the {{ post.displayName }} to populate in my browser, but replies aren't loading. Can anyone assist?
the JSON from the WebAPI:
[{"postId":1,"displayName":"Scott","message":"message1","replies":{"replyId":1,"displayName":"wayne","message":"test11"}},{"postId":2,"displayName":"Bill","message":"message12","replies":{"replyId":1,"displayName":"bob","message":"test21"}},{"postId":3,"displayName":"Wayne","message":"message12","replies":{"replyId":1,"displayName":"bob","message":"test21"}},{"postId":4,"displayName":"Bonnie","message":"message12","replies":{"replyId":1,"displayName":"bob","message":"test21"}},{"postId":5,"displayName":"Gina","message":"message12","replies":{"replyId":1,"displayName":"bob","message":"test21"}}]
My Service:
// This handles the database work for posting
gwApp.service('postService', function ($http, $q) {
// ---
// PUBLIC METHODS.
// ---
this.getPosts = function () {
var request = $http({
method: "get",
url: "http://localhost:59327/posts/details",
params: {
action: "get"
}
});
return (request.then(handleSuccess, handleError));
};
// ---
// PRIVATE METHODS.
// ---
// Transform the error response, unwrapping the application dta from
// the API response payload.
function handleError(response) {
// The API response from the server should be returned in a
// nomralized format. However, if the request was not handled by the
// server (or what not handles properly - ex. server error), then we
// may have to normalize it on our end, as best we can.
if (
!angular.isObject(response.data) ||
!response.data.message
) {
return ($q.reject("An unknown error occurred."));
}
// Otherwise, use expected error message.
return ($q.reject(response.data.message));
}
// Transform the successful response, unwrapping the application data
// from the API response payload.
function handleSuccess(response) {
return (response.data);
}
});
My Controller:
//This controller retrieves data from the services and associates then with the $scope
//The $scope is ultimately bound to the posts view
gwApp.controller('PostController', function ($scope, postService) {
$scope.posts = [];
loadRemoteData();
// public methods
// private methods
function applyRemoteData(newPosts) {
$scope.posts = newPosts;
}
function loadRemoteData() {
// $scope.posts = postService.getPosts();
postService.getPosts()
.then(
function (posts) {
applyRemoteData(posts);
}
);
}
});
My HTML code snippet:
this returns 3 blank table rows
<tr data-ng-repeat="reply in post.replies">
<td>
{{ reply.message }}
</td>
</tr>
This returns the valid data from my JSON:
<tr data-ng-repeat="post in posts">
<td>
PostId: {{ post.postId }} {{ post.displayName }}
</td>
</tr>
Any help would be much appreciated!
PLease see here: http://plnkr.co/edit/pMeopZwm2ZybIXvTRucy?p=preview
Your each post has only one object called replies, more likely that should be array of replays so you can access it like below :
<table>
<tr data-ng-repeat="post in posts">
<td>
PostId: {{ post.postId }} {{ post.displayName }}
<ul>
<li>{{post.replies.displayName}}: {{post.replies.message }}</li>
</ul>
</td>
</tr>
</table>
The answer by sss did work initially, but I got the best result when updating my JSON to use a list for the replies:
[{"postId":1,"displayName":"Scott","message":"message1","replies":[{"replyId":1,"displayName":"wayne","message":"test111"},{"replyId":2,"displayName":"bob","message":"test112"},{"replyId":3,"displayName":"bon","message":"test113"},{"replyId":4,"displayName":"ethan","message":"test114"}]},{"postId":2,"displayName":"Bill","message":"message12","replies":[{"replyId":1,"displayName":"wayne","message":"test211"},{"replyId":2,"displayName":"bob","message":"test212"}]},{"postId":3,"displayName":"Wayne","message":"message12","replies":[{"replyId":1,"displayName":"wayne","message":"test311"},{"replyId":2,"displayName":"bob","message":"test312"},{"replyId":3,"displayName":"bon","message":"test313"}]},{"postId":4,"displayName":"Bonnie","message":"message12","replies":[{"replyId":1,"displayName":"wayne","message":"test411"},{"replyId":2,"displayName":"bob","message":"test412"},{"replyId":3,"displayName":"bon","message":"test413"},{"replyId":3,"displayName":"bon","message":"test414"},{"replyId":4,"displayName":"ethan","message":"test415"}]},{"postId":5,"displayName":"Gina","message":"message12","replies":[{"replyId":1,"displayName":"wayne","message":"test511"},{"replyId":2,"displayName":"bob","message":"test512"},{"replyId":3,"displayName":"bon","message":"test513"},{"replyId":4,"displayName":"ethan","message":"test514"}]}]