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.
Related
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')
Vijay Anand asked this question yesterday, but it was closed before he got an answer:
HTTP Response:
{
"entry": {
"#xml:base": "https://API_PROC_SRV/",
"#xmlns": "http://www.w3.org/2005/Atom",
"#xmlns:m": "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata",
"#xmlns:d": "http://schemas.microsoft.com/ado/2007/08/dataservices",
"id": "https://API_PROC_SRV/A_Order",
"title": {
"#type": "text",
"#text": "A_Order()"
},
"updated": "2020-02-29T07:33:28Z",
"category": {
"#term": "Type",
"#scheme": "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"
},
"link": [],
"content": {
"#type": "application/xml",
"m:properties": {
"d:Order": "123456789"
}
}
}
}
Javascript code:
var json = response;
var order = json.object.entry.content['m:properties']['d:Order']; // I intend to read Order no from the below response.
Error (example, jsbin.com):
"TypeError: Cannot read property 'entry' of undefined
at null.js:27:25
at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:13924
at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:10866"
Per JSLint, the response is valid JSON.
json.object.entry is obviously wrong ... but
Q: What is the correct Javascript syntax to access the "order" value (named d:Order), when m:properties and d:Order both have semicolons in the name?
PS: I nominated Vijay's original question for re-opening ... but I'm not optimistic. Hence my new question.
You need to parse the JSON. And there's no object property anywhere, it's jut json.entry.content.
response = `{
"entry": {
"#xml:base": "https://API_PROC_SRV/",
"#xmlns": "http://www.w3.org/2005/Atom",
"#xmlns:m": "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata",
"#xmlns:d": "http://schemas.microsoft.com/ado/2007/08/dataservices",
"id": "https://API_PROC_SRV/A_Order",
"title": {
"#type": "text",
"#text": "A_Order()"
},
"updated": "2020-02-29T07:33:28Z",
"category": {
"#term": "Type",
"#scheme": "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"
},
"link": [],
"content": {
"#type": "application/xml",
"m:properties": {
"d:Order": "123456789"
}
}
}
}`;
var json = JSON.parse(response);
var order = json.entry.content['m:properties']['d:Order'];
console.log(order);
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 4 years ago.
I have this result JSON data for my api call, but when i try to access the data in the attribute "69106658_5" I cant, I am getting "Error: Uncaught SyntaxError: Invalid or unexpected token". I have a copy of what I am running on an online editoe below. I am guessing its because of the attribute contains an underscore.
let results=
{
"links": {
"data": {
"self": {
"body": "",
"content_type": "",
"href": "/api/v2/nodes/69107289/categories",
"method": "GET",
"name": ""
}
}
},
"results": [
{
"data": {
"categories": {
"58652374_10": [
"16",
"16.0.1",
"16.2",
"16.2.4"
],
"58652374_11": [
"English"
],
"58652374_12": [
"Windows"
],
"58652374_13": "2018-11-20T00:00:00",
"58652374_2": "Published",
"58652374_3": "19",
"58652374_4": "Video",
"58652374_5": "65",
"58652374_6": "How To",
"58652374_7": [
"basic"
],
"58652374_8": "237",
"58652374_9": "Content Server"
}
}
},
{
"data": {
"categories": {
"69106658_2": "You Tube",
"69106658_3": [
"End User"
],
"69106658_4": [
"69106508:7"
],
"69106658_5": "https://img.youtube.com/vi/j-aOeCpRvEs/hqdefault.jpg",
"69106658_6": false,
"69106658_7": "Engineering",
"69106658_8": null
}
}
}
]
}
var lookInto = results.results;
for( let key in lookInto ) {
var selectData = lookInto[key].data.categories;
console.log(selectData);
}
console.log( selectData.69106658_5 )
Attribute fields that begin with anything other than a letter (and some symbols like _), you have to use bracket notation to access.
Instead of selectData.69106658_5, try selectData['69106658_5']
The underscore shouldn't cause any problem.
If you want to access the property "69106658_5", you should do like this :
results.results[1].data.categories["69106658_5"]
I want to shorten a longLink with firebase and the REST API but I get the following response and I don't know what is wrong:
Response:
{
"error": {
"code": 400,
"message": "Long link is not parsable: https://www.google.de [https://firebase.google.com/docs/dynamic-links/rest#create_a_short_link_from_parameters]",
"status": "INVALID_ARGUMENT"
}
}
And this is how I do it:
The Request: https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=(hereismyapikey)
the Body lookes like this:
{
"longDynamicLink": "https://www.google.de",
"suffix": {
"option": "SHORT"
}
}
I tried first with the real URL I want to shorten. Same error. Than with google and with and without the http(s). I'm out of options and hope somebody sees what I did wrong here.
EDIT: Full Postman request:
"item": [
{
"name": "shortLinks",
"request": {
"method": "POST",
"header": [
{
"key": "Content-Type",
"value": "application/json"
}
],
"body": {
"mode": "raw",
"raw": "{\r\n \"longDynamicLink\": \"www.google.de\",\r\n \"suffix\": {\r\n \"option\": \"SHORT\"\r\n }\r\n}"
},
"url": {
"raw": "https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=xxx",
"protocol": "https",
"host": [
"firebasedynamiclinks",
"googleapis",
"com"
],
"path": [
"v1",
"shortLinks"
],
"query": [
{
"key": "key",
"value": "xxx"
}
]
}
},
"response": []
}
]
You are using the simple method for creating dynamic link which is roughly equals to the manual creation of dynamic link : https://firebase.google.com/docs/dynamic-links/create-manually
In the docs if you see the link passed in example carefully you will see the pattern as below:
https://your_subdomain.page.link/?link=your_deep_link&apn=package_name[&amv=minimum_version][&afl=fallback_link]
So you should format the input link according to this or create using the parameters which has very good breakdown of parameters in json:
https://firebase.google.com/docs/dynamic-links/rest#create_a_short_link_from_parameters
Here is the api reference for firebase dynamic link creation from parameters:
https://firebase.google.com/docs/reference/dynamic-links/link-shortener#parameters
I find the JSON parameter method is easier.
var body = {
"dynamicLinkInfo": {
"dynamicLinkDomain": "yourcustom.page.link",
"link": fileUrl
},
"suffix": {
"option": "SHORT"
}
};
Then if you're using Node. The node-fetch package REST call would work like:
var fetchFileUrl = fetch(YOUR_SHORTLINK_URL, {
method: 'POST',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
}).then(function(response){
return response.json();
});
This question already has answers here:
Access-Control-Allow-Origin error sending a jQuery Post to Google API's
(7 answers)
Closed 8 years ago.
I'm trying to fetch and parse json data so I could output it to a blank HTML file. The problem that keeps occurring to me is that if I fetch the data and parse it I get a Uncaught TypeError: Cannot read property 'SOCENGPRE' of undefined error. If I fetch the json data in dataType: "text" format I get the XMLHttpRequest cannot load <api url> No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. error. The website is on a local machine and I cannot edit the server to be cross-platformed because of person reasons. The code looks like this :
var myDataVar;
function main() {
$.ajax({
url: "http://api&leagues=SOCENGPRE&format=jsonp&callback=?",
dataType: "json",
success: function (data) {
myDataVar = $.parseJSON(data);
getUpcomingFixtures();
}
});
}
function getUpcomingFixtures() {
for (var i = 0; i <= myDataVar.SOCENGPRE.fixtures.length - 1; i++) {
console.log(myDataVar.SOCENGPRE.fixtures[i].id);
console.log(myDataVar.SOCENGPRE.fixtures[i].home_team + " vs " + myDataVar.SOCENGPRE.fixtures[i].away_team);
}
}
An example of the data being fetched looks like this :
{
"SOCENGPRE": {
"league_name": "Barclays Premier League",
"league_phid": null,
"league_type": null,
"fixtures": [{
"id": "64714",
"code": "SOCENGPRE",
"event_slug": "west_ham-tottenham-1401290",
"start": "1399117500",
"home_team": "West Ham",
"home_team_phid": null,
"home_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t523.png",
"home_team_short": "",
"away_team": "Tottenham",
"away_team_phid": null,
"away_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t498.png",
"away_team_short": "",
"phid": null
}, {
"id": "64711",
"code": "SOCENGPRE",
"event_slug": "manchester_u-sunderland-1401286",
"start": "1399125600",
"home_team": "Manchester U",
"home_team_phid": null,
"home_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t20790.png",
"home_team_short": "Man U",
"away_team": "Sunderland",
"away_team_phid": null,
"away_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t382.png",
"away_team_short": "",
"phid": null
}, {
"id": "64712",
"code": "SOCENGPRE",
"event_slug": "stoke-fulham-1401288",
"start": "1399125600",
"home_team": "Stoke",
"home_team_phid": null,
"home_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t389.png",
"home_team_short": "",
"away_team": "Fulham",
"away_team_phid": null,
"away_team_logo": "\/\/dxnxhx88pdxyv.cloudfront.net\/logo\/32\/t379.png",
"away_team_short": "",
"phid": null
}]
}
}
My goal is to just fetch the fixture id and the two teams competing. Any clue what I'm doing wrong?
Try using the below code , don't parse the JSON again as it is already handled, assuming string is your JSON object.
At beginning of script declare this variable result as array;
var result = [];
function getUpcomingFixtures() {
$.each( string , function ( i , val) {
$.each( val['fixtures'] , function ( k , fixturesData) {
result.push( { id: fixturesData.id ,
hometeam : fixturesData.home_team ,
awayteam : fixturesData.away_team
}
);
});
});
}