I am learning angular js from ground up and am currently trying to retrieve data from a json file.
I am using - nodejs, express, AngularJS.
Earlier I was getting an error "Unexpected token D" on using -
$http.get("/models/driversList.json").success(function(response){$scope.driversList = response})
which got resolved but now I'm getting something like this with the current code -
Drivers Championship Standings
1
I'm guessing the response is basically blank and therefore the "1" but am not getting as to why that is happening.
Below are my files -
/app.js
app.use('/models',express.static(path.join(__dirname, 'private/data/db/models')));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/scripts',express.static(path.join(__dirname, 'public/javascripts')));
app.use('/styles',express.static(path.join(__dirname, 'public/stylesheets')));
/javascripts/app.js
angular.module('F1FeederApp', [
'F1FeederApp.controllers'
]);
/javascripts/controllers.js
angular.module('F1FeederApp.controllers', []).
controller('driversController', function($scope, $http) {
$http({
method: 'GET',
url: '/models/driversList.json',
data: {},
transformResponse: function (data, headersGetter, status) {
//This was implemented since the REST service is returning a plain/text response
//and angularJS $http module can't parse the response like that.
return {data: data};
}
}).success(function(response){ alert('worked'); $scope.driversList = response}).error(function(response) {
$scope.driversList = [
{
Driver: {
givenName: response,
familyName: 'Vettel'
},
points: 322,
nationality: "German",
Constructors: [
{name: "Red Bull"}
]
},
{
Driver: {
givenName: 'Fernando',
familyName: 'Alonso'
},
points: 207,
nationality: "Spanish",
Constructors: [
{name: "Ferrari"}
]
}
];
})
});
driversList.json
[
{
Driver: {
givenName: 'Eldorado',
familyName: 'Vettel'
},
points: 322,
nationality: "German",
Constructors: [
{name: "Red Bull"}
]
},
{
Driver: {
givenName: 'Fernando',
familyName: 'Alonso'
},
points: 207,
nationality: "Spanish",
Constructors: [
{name: "Ferrari"}
]
}
]
index.html
<!DOCTYPE html>
<html>
<head>
<title>F-1 Feeder</title>
<script src="/scripts/angular.min.js"></script>
<script src="/scripts/controllers.js"></script>
<script src="/scripts/app.js"></script>
</head>
<body ng-app="F1FeederApp" ng-controller="driversController">
<table>
<thead>
<tr><th colspan="4">Drivers Championship Standings</th></tr>
</thead>
<tbody>
<tr ng-repeat="driver in driversList">
<td>{{$index + 1}}</td>
<td>
{{driver.Driver.givenName}} {{driver.Driver.familyName}}
</td>
<td>{{driver.Constructors[0].name}}</td>
<td>{{driver.points}}</td>
</tr>
</tbody>
</table>
</body>
</html>
EDIT:
#rattanak
To answer the point 3, yes it works if I simply assign the array variable to the scope variable. The part in error() is the one which was working previously.
I also tried point 1 and it seems the json is present in "data", so I assigned response.data to driversList and now am getting this error -
Data:
[{Driver:{givenName:'Eldorado',familyName:'Vettel'},points:322,nationality:"German",Constructors:[{name:"Red Bull"}]}]
Error: [ngRepeat:dupes] http://errors.angularjs.org/1.4.7/ngRepeat/dupes?p0=driver%20in%20driversList.data&p1=string%3Ar&p2=r
at Error (native)
at http://localhost:3000/scripts/angular.min.js:6:416
at http://localhost:3000/scripts/angular.min.js:280:39
at Object.fn (http://localhost:3000/scripts/angular.min.js:129:401)
at n.a.$get.n.$digest (http://localhost:3000/scripts/angular.min.js:130:483)
at n.a.$get.n.$apply (http://localhost:3000/scripts/angular.min.js:133:512)
at h (http://localhost:3000/scripts/angular.min.js:87:376)
at K (http://localhost:3000/scripts/angular.min.js:91:499)
at XMLHttpRequest.z.onload (http://localhost:3000/scripts/angular.min.js:93:37)
indicating that there are duplicates
Your file driverlist.json does not contain valid JSON code. This code should be:
[
{
"Driver": {
"givenName": "Eldorado",
"familyName": "Vettel" },
"points": 322,
"nationality": "German",
"Constructors": [
{"name": "Red Bull"}
]
},
{
"Driver": {
"givenName": "Fernando",
"familyName": "Alonso"
},
"points": 207,
"nationality": "Spanish",
"Constructors": [
{"name": "Ferrari"}
]
}
]
Correct this and try again.
JSON always use double quotes (") never single quotes (')
For more info on correct JSON, see http://www.json.org/
It seems like the $http service does not resolve successfully. It is hard to tell without actually testing the code. With Chrome Dev Console, I would debug the code by:
Use console.log($scope.driversList) in the success function of the promise.
Use console.log(error) in the error function of the promise.
Were you able to get the code to work without using $http service, namely just assign array variable of the data to $scope.driversList.
I am happy to test it for you if you can provide a github link or something.
Related
I used the code to convert json data from Yarn REST API to Prometheus data type:
https://github.com/prometheus-community/json_exporter.
However, it printed errors:
level=error ts=2021-07-08T06:31:03.712Z caller=collector.go:83 msg="Failed to extract value for metric" path={.capacity} err="capacity is not found" metric="Desc{fqName: "queues_capacity", help: "information on queues", constLabels: {}, variableLabels: [type]}"
I was wondering if there is some wrong in my configuration of YAML file (such as in terms of nested json) or just the reason about the code.
my yaml config is:
metrics:
- name: queues
path: "{ .scheduler.schedulerInfo.queues.queue }"
help: information on queues
type: object
labels:
type: '{.type}'
values:
capacity: '{.capacity}'
and part of the json file is:
{
"scheduler": {
"schedulerInfo": {
"type": "capacityScheduler",
"capacity": 100,
"usedCapacity": 1.0526316,
"maxCapacity": 100,
"queueName": "root",
"queues": {
"queue": [
{
"type": "capacitySchedulerLeafQueueInfo",
"capacity": 10,
"usedCapacity": 10.526316,
"maxCapacity": 100,
use [*] to get all object first, so it should be:
path: "{ .scheduler.schedulerInfo.queues.queue[*] }"
according to this: https://kubernetes.io/docs/reference/kubectl/jsonpath/
I am using BoostrapTable in an MVC application. The controller is returning some data as follows:
model.DataAsJson = JsonConvert.SerializeObject(model.Entities.Select(x => x.DataProperties));
My client side looks like this (snippet):
<table id="table"></table>
<script type="text/javascript">
$('#table').bootstrapTable({
data: '#Model.DataAsJson',
//url: 'ms.json',
columns: [{
field: 'ClientFileNo',
title: 'Case No'
}, {
field: 'ClientName',
title: 'Customer Name'
}]
});
The resulting Json looks like this:
[{
"RowNum": "2",
"ID": "XXX",
"ClientFileNo": "XXX",
"Description": "XXX",
"ClientName": "XXX",
"TypeDescription": "XXX",
"PrincipleName": "XXX",
"Created": "2017-11-08T10:31:23.673Z"
},
{
"RowNum": "3",
"ID": "XXX",
"ClientFileNo": "XXX",
"Description": "XXX",
"ClientName": "XXX",
"TypeDescription": "XXX",
"PrincipleName": "XXX",
"Created": "2017-11-01T12:29:08.763Z"
}
]
If I paste the result of the SerializeObject() call into a json file and pass to the url property, the table populates as expected. However, if I use the data property and #Model.DataAsJson then I have thousands of empty rows in my table with a '-' in each column.
I have seen a reference to the responseHandler property and I have tried providing a name to my JSON array as follows however it has not fixed my issue:
model.DataAsJson = JsonConvert.SerializeObject(new
{
jsonData = model.Entities.Select(x => x.DataProperties)
});
<script type="text/javascript">
$('#table').bootstrapTable({
data: '#Model.DataAsJson',
responseHandler: function (res) {
res.jsonData
},
Can anyone see why this would happen?
Ok got to the bottom of this in case someone else gets caught by it.
I modified the js to read the model data as following:
$('#table').bootstrapTable({
data: #Html.Raw(Model.DataAsJson)
So I removed the apostrophes and added the Html.Raw. I realised this by viewing the data in Chrome debugger and could see it was encoded. Also, I was having some further issues as the legacy codebase I am working with had the script in a partial view and the Chrome debugger was not hitting the debug points. I sorted this by adding:
debugger;
where I wanted it to break.
Thanks and hope this helps others.
I'm using google apps script to create assignment with an uploaded document for a classroom. However, there's an error.
Execution failed: Invalid JSON payload received. Unknown name
"share_mode" at 'course_work.materials[0]': Cannot find field. Invalid
JSON payload received. Unknown name "id" at
'course_work.materials[0].drive_file': Cannot find field. Invalid JSON
payload received. Unknown name "title" at
'course_work.materials[0].drive_file': Cannot find field. (line 2,
file "TEST") [0.061 seconds total runtime]
Here's my code. I know the error is in materials but I'm not sure what I did wrongly.
function myFunction() {
var exec = Classroom.Courses.CourseWork.create({
title: "Test File",
state: "DRAFT",
materials: [
{
driveFile: {id: "1ENk55RMtApIydyPFe0uyuhmu6nSV4", title: "Test File"},
shareMode: "STUDENT_COPY"
}
],
workType: "ASSIGNMENT"
}, "3896298178");
Logger.log(exec);
}
Found out the root of your issue. I've updated your codes to make it work.
Request:
function myFunction() {
var ClassSource = {
title: "Test File",
state: "DRAFT",
materials: [
{
driveFile:{
driveFile: {
id: "fileID",
title: "Sample Document"
},
shareMode: "STUDENT_COPY"
}
}
],
workType: "ASSIGNMENT"
};
Classroom.Courses.CourseWork.create(ClassSource, COURSEID)
//Logger.log(exec);
}
Result:
We receive Invalid JSON payload received. because the formating of the request is wrong. Its a little bit more complicated than I thought, that is why I tried using Try this API to see the request format and it really helped me solve your issue.
Hope this helps.
Per the docs Drivefile property title is marked read only. Just use the id.
https://developers.google.com/classroom/reference/rest/v1/DriveFile
Following ajax request can be sent to create the assignment. The code below was written for Angular but it can be easily converted to jQuery script. You can build your own courseWork object that is being passed as 'data' of ajax request to see the full Object structure visit CourseWork API
$http({
url: 'https://classroom.googleapis.com/v1/courses/'+courseId+'/courseWork?access_token='+$scope.session.access_token,
method: 'POST',
data:{
"title": title,
"description": description,
"state": "PUBLISHED",
"workType": "ASSIGNMENT",
"submissionModificationMode": "MODIFIABLE_UNTIL_TURNED_IN",
"associatedWithDeveloper": true
}
}).then(function(response){
console.log(response);
if(response.status==200){
}
}, function(response){
console.log(response);
});
}
So I'm trying to load the data received from a webservice into a sencha touch 2 store.
The data is nested JSON, however it is made to include multiple dataArrays.
I am working with sencha touch 2.3.1, somewhat equal to Ext JS 4.2. I don't have that much experience with sencha yet, but I'm getting there. I decided to go for MVC, so I'd like the answers to be as close to this as possible :).
This is the example JSON I am using:
[
{
"DataCollection": {
"DataArrayOne": [
{
"Name": "John Smith",
"Age": "19"
},
{
"Name": "Bart Smith",
"Age": "16"
}
],
"DataArrayTwo": [
{
"Date": "20110601",
"Product": "Apple",
"Descr": "",
"Remark": ""
},
{
"Date": "20110601",
"Product": "Orange",
"Descr": "",
"Remark": ""
},
{
"Date": "20110601",
"Product": "Pear",
"Descr": "",
"Remark": ""
}
],
"DataArrayThree": [
{
"SomeTotalCost": "400,50",
"IntrestPercentage": "3"
}
]
}
}
]
Through only one call, I get this json. I don't want to cause any unnecessary traffic so I hope to be able to use the data somehow.
I want to be able to use each DataArray on its own.
The data gets sent to the store through its proxy:
Ext.define("MyApp.store.myDataObjects", {
extend: "Ext.data.Store",
config: {
model: "MyApp.model.myDataObject",
proxy: {
reader: {
type: "json",
rootProperty: "DataCollection"
},
type: "ajax",
api: {
read: "https://localhost/Service.svc/json"
},
limitParam: false,
startParam: false,
pageParam: false,
extraParams: {
id: "",
token: "",
filter: ""
},
writer: {
encodeRequest: true,
type: "json"
}
}
}
});
I am a bit stuck with the model here. I tried using mappings which would look like this:
config: {
fields: [ {
name: "IntrestPercentage",
mapping: "Calculation.IntrestPercentage",
type: "string"
}
]}
I tried associations as well but to no avail.
According to google chrome console, it doesn't make any objects containing data. I get only 1 object with all values "null".
My endgoal is to be able to show each dataArray in a separate table. So a table for DataArrayOne, a table for DatarrayTwo... The data itself isn't linked. They are only details that have to be shown on a view.
John Smith isn't related to the apples, as in he didn't buy. The apples are just there as an item to be shown.
The possible solutions I've seen yet not understood due to them being outdated are:
ChildStores: You have a master store that receives the data, and then
you split the data to other stores according to rootProperty. I have
no idea how to do this however and I'm not sure if it will work at
all.
Associations, in case I was doing them wrong. I don't think they
are needed because the data isn't linked to each other but it is part
of "DataCollection" though.
Could someone please post an example on how to deal with this unusual(?) kind of nested json.
Or any other solution which will lead to being able to use the 3 dataArrays at will.
Thanks in advance
The best would be to load the complete data with a separate Ext.Ajax.request and then use store.loadData in the success callback. For example:
var data = Ext.decode(response.responseText);
store1.loadData(data[0].DataCollection.DataArrayOne);
store2.loadData(data[0].DataCollection.DataArrayTwo);
store3.loadData(data[0].DataCollection.DataArrayThree);
jQuery Code:
$(document).ready(function(){
$.getJSON('dat.js', function(data) {
var obj = JSON.parse(data);
alert(obj[0].title);
});
});
My JSON file :
{
"posts":
[
{
"title": "ajax | Programming ",
"url": "hello"
},
{
"title": "jQuery and Ajax Demos Pard - 3",
"url": "how are you"
},
]
}
Its giving me an error JSON.parse:unexpected character. But when I tried to do it by taking the json inside an array its ok then. I want to access the data from json file itself
you do parseJSON when your input is a json string and u expect an object. Here, getJSON is already giving u the response as an object.
try this
$(document).ready(function(){
$.getJSON('dat.js', function(obj) {
alert(obj.posts[0].title);
});
});
A Quick jslint check says that you have invalid json at line 11 },, Try removing the comma from the last member of "posts" and see if that help
{
"title": "jQuery and Ajax Demos Pard - 3",
"url": "how are you"
}, <---- THIS