$http service throw exception when downloading json file from server - javascript

When trying to download a file from server i use $http service as following:
$http({url: url, method: "GET", withCredentials: true});
for some unkown reason only json files causing an exception when getting from server:
SyntaxError: Unexpected token ] in JSON at position 1362
at Object.parse (native)
at tc (https://sharon-staging.comilion.com/app/bower_components/angular/angular.min.js:14:245)
at bc (https://sharon-staging.comilion.com/app/bower_components/angular/angular.min.js:77:7)
at https://sharon-staging.comilion.com/app/bower_components/angular/angular.min.js:77:369
at q (https://sharon-staging.comilion.com/app/bower_components/angular/angular.min.js:7:322)
at dd (https://sharon-staging.comilion.com/app/bower_components/angular/angular.min.js:77:351)
at c (https://sharon-staging.comilion.com/app/bower_components/angular/angular.min.js:78:495)
at https://sharon-staging.comilion.com/app/bower_components/angular/angular.min.js:112:182
at m.$eval (https://sharon-staging.comilion.com/app/bower_components/angular/angular.min.js:126:250)
at m.$digest (https://sharon-staging.comilion.com/app/bower_components/angular/angular.min.js:123:365)
The json file is valid, i attached him in the question.
if it's a text file, or even the same file that i added a comment above the json, there is no exception.
If anyone have an idea why do i get this error, it will really really help :)
Thanks
not working file:
{
"users": [
{
"email": "D_user1#e2e.com",
"nickName": "D_user1e2e"
}
],
"groups": [
{
"name": "D_BETWEEN_INSTANCES",
"description": "GROUP OF USERS FROM ALL INSTANCES",
"members": [
"user6#e2e.com",
"A_user6#e2e.com",
"B_user6#e2e.com",
"D_user1#e2e.com"
]
},
]
}
working file:
tests
{
"users": [
{
"email": "D_user1#e2e.com",
"nickName": "D_user1e2e"
}
],
"groups": [
{
"name": "D_BETWEEN_INSTANCES",
"description": "GROUP OF USERS FROM ALL INSTANCES",
"members": [
"user6#e2e.com",
"A_user6#e2e.com",
"B_user6#e2e.com",
"D_user1#e2e.com"
]
},
]
}

Remove the , sign from here-
"D_user1#e2e.com"
]
},
like this-
"D_user1#e2e.com"
]
}

Related

Issues adding sessions and information to the Google Fit REST Api using JS

So I am reasonably new to using API's with Js but I am struggling a lot to understand how the Google Fit API works. I am attempting to add a new Workout's data to the API by adding a session and some data for the intensity (heart points) of the session. I can get the session to appear correctly but run into constant errors when I try to create a dataSource and add a point to it for the session. It would be greatly appreciated if someone could help me to fix my code to achieve this or could direct me to a more thorough example of similar code as the API docs don't seem to be too well detailed with examples etc. Thanks in advance.
Here's the 3 api calls that I have written so far, one for creating the DataSource, one for the DataPoint and one for the Session. The session works correctly and adds a session of 1 hr for the correct activity but I am unable to get any of the other API requests to work.
Data Source :
``gapi.client.fitness.users.dataSources.create({
"userId":"me",
"resource": {
"application": {
"name": "LittleWorkouts"
},
"dataType": {"field":[{
"format": "floatPoint",
"name": "com.google.heart_minutes"
}],
"name": "com.google.heart_minutes"
},
"device": {
"manufacturer": "op",
"model": "6",
"type": "phone",
"uid": "1000019",
"version": "1"
},
"type": "raw"
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error 1", err); });
``
Data Point :
``
gapi.client.fitness.users.dataSources.datasets.patch({
"dataSourceId":"raw:com.google.heart_minutes:292824132082:op:6:1000019",
"userId": "me",
"datasetId": "1592087806561000000-1592287806561000000",
"resource": {
"minStartTimeNs": "1592087806561000000",
"maxEndTimeNs": "1592287806561000000",
"dataSourceId": "raw:com.google.heart_minutes:292824132082:op:6:1000019",
"point": [
{
"startTimeNanos": "1592087806561000000",
"endTimeNanos": "1592287806561000000",
"value": [
{
"fpVal": 89.1
}
],
"dataTypeName": "com.google.heart_minutes"
}
]
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error 2", err); });
``
Session :
``gapi.client.fitness.users.sessions.update({
"userId":"me",
"sessionId": "someSessionId19",
"id": "someSessionId19",
"name": "Awesome Workout19",
"description": "A very intense workout",
"startTimeMillis": new Date().getTime() - 3600000,
"endTimeMillis": new Date().getTime(),
"version": 1,
"lastModifiedToken": "exampleToken",
"application": {
"detailsUrl": "http://example.com",
"name": "LittleWorkouts",
"version": "1.0"
},
"activityType": 21,
"activeTimeMillis": 3600000
}).then((res) => {console.log(res)});
console.log('res')
//request.execute((res) => {console.log(res);console.log('executrd')})
console.log(auth2.currentUser.get().getBasicProfile().getGivenName());
var request2 = gapi.client.fitness.users.sessions.list({
"userId":"me"
}).then((res) => {console.log(res)})
``
Error message
{message: "Unable to fetch DataSource for Dataset: raw:com.google.heart_minutes:292824132082:op:6:1000019", domain: "global", reason: "invalidArgument"}
It looks like it could be that you're trying to pass in the wrong fields for the data type: if you want to use a standard data type (like com.google.heart_minutes), you should either pass the exact fields of the standard data type (the field should be called "intensity"); or just pass the data type name, and the backend will fill them in for you.
So, if you change the data type to
"dataType": {"name": "com.google.heart_minutes"}
It should work.
Then, you need to use the data source ID returned from that request for the data points.
Awesome, so after some support in the comments I have some working code to add a new session with data from a previously defined data source using 3 API calls. The first call is to create a data source and only needs to be run once. The second and third then add a data point to a data set and creates a new session for the workout respectively. Here's the final working code:
Data Source:
/*
gapi.client.fitness.users.dataSources.create({
"userId":"me",
"resource": {
"application": {
"name": "LittleWorkouts"
},
"dataType": {
"name": "com.google.heart_minutes"
},
"device": {
"manufacturer": "op",
"model": "6",
"type": "phone",
"uid": "1000020",
"version": "1"
},
"type": "raw"
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error 1", err); });
*/
Data and Data Set:
gapi.client.fitness.users.dataSources.datasets.patch({
"dataSourceId":"raw:com.google.heart_minutes:108881196053:op:6:1000020",
"userId": "me",
"datasetId": z,
"resource": {
"minStartTimeNs": workoutStartTime * 1000000,
"maxEndTimeNs": workoutEndTime * 1000000,
"dataSourceId": "raw:com.google.heart_minutes:108881196053:op:6:1000020",
"point": [
{
"originDataSourceId": "raw:com.google.heart_minutes:108881196053:op:6:1000020",
"value": [
{
"fpVal": 8
}
],
"dataTypeName": "com.google.heart_minutes",
"endTimeNanos": workoutEndTime * 1000000,
"startTimeNanos": workoutStartTime * 1000000,
}
]
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error 2", err); });
Session:
gapi.client.fitness.users.sessions.update({
"userId":"me",
"sessionId": id,
"id": id,
"name": "Morning Workout",
"description": "A very intense workout",
"startTimeMillis": workoutStartTime,
"endTimeMillis": workoutEndTime,
"version": 1,
"lastModifiedToken": "exampleToken",
"application": {
"detailsUrl": "http://example.com",
"name": "LittleWorkouts",
"version": "1.0"
},
"activityType": 21,
"activeTimeMillis": workoutEndTime - workoutStartTime
}).then((res) => {console.log(res)});
console.log('res')

How can I change the status code of App sync AWS?

That's the error data returned from App Sync AWS:
{
"data": {
"getContentById": null
},
"errors": [
{
"path": [
"getContentById"
],
"data": null,
"errorType": "Lambda:Handled",
"errorInfo": null,
"locations": [
{
"line": 1,
"column": 2,
"sourceName": null
}
],
"message": "ID is not found"
}
]
}
How can I change the 200 Status code from my lambda function?
Screen shot from PostMan
Currently you cannot customize the error status code in AWS AppSync. The suggested approach is to use errorType in the error response. You can use $util.appendError or $util.error methods in your velocity mapping template to define the error type.

How to modify json data in fiddler.

I am gettring one issue so I want to change the day in fiddler,
which after ajax request I am getting this json data.
{
"ROOT": {
"DATA": {
"I": [
[
"ABC",
"123"
],
[
"DEF",
"124"
],
[
"GHI",
"125"
]
]
}
}
}
Now in fiddler url I want to change this like below.
{
"ROOT": {
"DATA": {
"I": [
[
"DEF",
"124"
],
[
"GHI",
"125"
]
]
}
}
}
Is there any way I can change data in fiddler by clicking on my url
Yes, there is a way. Go to Fiddler, right click on the url and then go to Replay -> Reissue and Edit
Now on the right side go to Inspectors -> TextView. You will see the json data that you want to change. Do the changes and then click on Run To Completion to hit the same url with the CHANGED data.

JSON Lint validated JSON String but the same doesnt gets parsed with JS

I have built a Automation Test Framework using TestNG + Selenium where I am generating a HTML Report at the end of the execution.
I am passing the execution details directly as JSON string (as we are not hosting the report into a webserver, this is a local setup) within the HTML file and running an internal JS to populated the data into the report grid.
Everything is working fine, except that once I get an exception I am trying to report the stacktrace in HTML which again gets into the report as a JSON value and JS denies to parse it.
To the understand the problem better, please check the code snippet below
// This is where I am reporting the exception
public static void ReportException(Exception e){
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
BuildReport(itrStepCnt,"Exception Occurred!",StringEscapeUtils.escapeJson("Exception Details - "+sw.toString()),"ERROR",captureScreenshot());
ItrConcludeReport();
}
and the converting a map to JSON String and finally reporting to HTML
content = content.replaceAll("#testrepdt#",finalContent);
JS is trying to parse it as following and fails to do the samr
var jsondata = JSON.parse(dt);
Here is the JSON String which gets validated with Lint but didnt gets passed through JSON Parser
[
{
"testclasspath": "app.applicationa.testcases.module1",
"testcasename": "TC004",
"executiontime": "5799ms",
"teststatus": "PASS",
"iteration": [
{
"teststeps": [
{
"Status": "PASS",
"Description": "pass desc",
"StepNo": "1",
"StepName": "StepName 1:1",
"Snapshot": "./SNAPSHOTS/15_Nov_2015_020306095_73350.png"
}
],
"itrname": "Iteration: 1"
},
{
"teststeps": [
{
"Status": "PASS",
"Description": "pass desc",
"StepNo": "1",
"StepName": "StepName 1:2",
"Snapshot": "./SNAPSHOTS/15_Nov_2015_020306291_46233.png"
}
],
"itrname": "Iteration: 2"
},
{
"teststeps": [
{
"Status": "PASS",
"Description": "pass desc",
"StepNo": "1",
"StepName": "StepName 1:3",
"Snapshot": "./SNAPSHOTS/15_Nov_2015_020306481_36460.png"
}
],
"itrname": "Iteration: 3"
}
]
},
{
"testclasspath": "app.applicationa.testcases.module1",
"testcasename": "TC002",
"executiontime": "6025ms",
"teststatus": "PASS",
"iteration": [
{
"teststeps": [
{
"Status": "PASS",
"Description": "pass desc",
"StepNo": "1",
"StepName": "StepName 1:3",
"Snapshot": "Not Required"
},
{
"Status": "ERROR",
"Description": "Exception Details - java.lang.NullPointerException\\r\\n\\tat app.applicationa.testcases.module1.TC002(module1.java:64)\\r\\n\\tat sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\\r\\n\\tat sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)\\r\\n\\tat sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)\\r\\n\\tat java.lang.reflect.Method.invoke(Unknown Source)\\r\\n\\tat org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)\\r\\n\\tat org.testng.internal.Invoker.invokeMethod(Invoker.java:639)\\r\\n\\tat org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)\\r\\n\\tat org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)\\r\\n\\tat org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)\\r\\n\\tat org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)\\r\\n\\tat org.testng.TestRunner.privateRun(TestRunner.java:774)\\r\\n\\tat org.testng.TestRunner.run(TestRunner.java:624)\\r\\n\\tat org.testng.SuiteRunner.runTest(SuiteRunner.java:359)\\r\\n\\tat org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)\\r\\n\\tat org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)\\r\\n\\tat org.testng.SuiteRunner.run(SuiteRunner.java:261)\\r\\n\\tat org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)\\r\\n\\tat org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)\\r\\n\\tat org.testng.TestNG.runSuitesSequentially(TestNG.java:1191)\\r\\n\\tat org.testng.TestNG.runSuitesLocally(TestNG.java:1116)\\r\\n\\tat org.testng.TestNG.run(TestNG.java:1024)\\r\\n\\tat org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:112)\\r\\n\\tat org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:205)\\r\\n\\tat org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:176)\\r\\n",
"StepNo": "1",
"StepName": "Exception Occurred!",
"Snapshot": "./SNAPSHOTS/null"
}
],
"itrname": "Iteration : 1"
}
]
}
]

Invalid JSON,Unexpected Token [duplicate]

This question already has an answer here:
AngularJS $http.post error Unexpected token F
(1 answer)
Closed 7 years ago.
I'm trying to send JSON data to server using angular, But getting JSON.parse error in firefox and Unexpected token in chrome.
It works sometime and throws error sometime.
I consider it is because of the timestamp I'm using to create some keys.
{
"genericformfieldId": "1",
"userId": "2",
"formData": {
"_1443551400000": [
{
"mValue": "HARYANA",
"type": "DropDown",
"name": "selectState"
}
],
"_1443637800000": [
{
"mValue": "CHHATTISGARH",
"type": "DropDown",
"name": "selectState"
}
],
"_1443810600000": [
{
"mValue": "sac",
"type": "SingleLineText",
"name": "departureFrom"
}
]
}
}
Please suggest.
Adding code for posting data
$http({
method: 'POST',
url: Url,
headers: { "Content-Type": "application/json" },
data: formData
})
.success( function( response, status, headers, config ) {
console.log( response );
if( response ) {
deferred.resolve( response );
}
})
.error( function( response, status, headers, config ) {
deferred.reject( null );
});
If you JSON.parse an object the "Unexpected token o" is thrown simply because you are trying to parse object.toString(), which is [object Object]. Try to JSON.parse('[object Object]'); ;)
This should work for you
var data = '{
"genericformfieldId": "1",
"userId": "2",
"formData": {
"_1443551400000": [
{
"mValue": "HARYANA",
"type": "DropDown",
"name": "selectState"
}
],
"_1443637800000": [
{
"mValue": "CHHATTISGARH",
"type": "DropDown",
"name": "selectState"
}
],
"_1443810600000": [
{
"mValue": "sac",
"type": "SingleLineText",
"name": "departureFrom"
}
]
}
}';
JSON.parse(data);
This answer https://stackoverflow.com/a/12719860/1868660 explains
Unexpected token ILLEGAL(…) issue
You must clean input json.
Check this:
https://jsfiddle.net/am190cv5/
Here's the source:
var s = '{"genericformfieldId": "1","userId": "2","formData": {"_1443551400000": [{"mValue": "HARYANA","type": "DropDown","name": "selectState"}],"_1443637800000": [{"mValue": "CHHATTISGARH","type": "DropDown","name": "selectState"}],"_1443810600000": [{"mValue": "sac","type": "SingleLineText","name": "departureFrom"}]}}';
var result = JSON.parse(s);
console.log(result);
Open the console and look the result.

Categories

Resources