I am getting a response from authorize.net payment gateway and tried many times and many ways to parse it but no luck.
Here is the main response from authorize.net:
"{"transactionResponse":{"responseCode":"1","authCode":"XXXXXX","avsResultCode":"Y","cvvResultCode":"P","cavvResultCode":"2","transId":"11111111111","refTransID":"","transHash":"","testRequest":"0","accountNumber":"XXXX0002","accountType":"AmericanExpress","messages":[{"code":"1","description":"This transaction has been approved."}],"transHashSha2":"2E6533BDC93C975EE3C1134B7421A337D5B8FB9C257437DB8B4XXXX4BCD92024B33704B811C69E58527359CA8628E8E33E55AA68B881E6F3D15B5F2FEAEB490B","SupplementalDataQualificationIndicator":0,"networkTransId":"HLH5UGDQFZ98LHRLDGIZEG7"},"messages":{"resultCode":"Ok","message":[{"code":"I00001","text":"Successful."}]}}"
I am following this tutorial.
I have tried this:
const result = JSON.parse(JSON.stringify(res.response));
console.log('1', result);
And result is:
1 {"transactionResponse":{"responseCode":"1","authCode":"9UQISS","avsResultCode":"Y","cvvResultCode":"P","cavvResultCode":"2","transId":"60164579108","refTransID":"","transHash":"","testRequest":"0","accountNumber":"XXXX0002","accountType":"AmericanExpress","messages":[{"code":"1","description":"This transaction has been approved."}],"transHashSha2":"2E6533BDC93C975EE3C1134B7421A337D5B8FB9C257437DB8B4DA924BCD92024B33704B811C69E58527359CA8628E8E33E55AA68B881E6F3D15B5F2FEAEB490B","SupplementalDataQualificationIndicator":0,"networkTransId":"HLH5UGDQFZ98LHRLDGIZEG7"},"messages":{"resultCode":"Ok","message":[{"code":"I00001","text":"Successful."}]}}
I want result like this:
{
"transactionResponse": {
"responseCode": "1",
"authCode": "XXXXXX",
"avsResultCode": "Y",
"cvvResultCode": "P",
"cavvResultCode": "2",
"transId": "11111111111",
"refTransID": "",
"transHash": "",
"testRequest": "0",
"accountNumber": "XXXX0002",
"accountType": "AmericanExpress",
"messages": [
{
"code": "1",
"description": "This transaction has been approved."
}
],
"transHashSha2": "2E6533BDC93C975EE3C1134B7421A337D5B8FB9C257437DB8B4XXXX4BCD92024B33704B811C69E58527359CA8628E8E33E55AA68B881E6F3D15B5F2FEAEB490B",
"SupplementalDataQualificationIndicator": 0,
"networkTransId": "HLH5UGDQFZ98LHRLDGIZEG7"
},
"messages": {
"resultCode": "Ok",
"message": [
{
"code": "I00001",
"text": "Successful."
}
]
}
}
Please guide me...
This is the Answer to my question:
I am getting this data in res.response:
"{"transactionResponse":{"responseCode":"1","authCode":"XXXXXX","avsResultCode":"Y","cvvResultCode":"P","cavvResultCode":"2","transId":"11111111111","refTransID":"","transHash":"","testRequest":"0","accountNumber":"XXXX0002","accountType":"AmericanExpress","messages":[{"code":"1","description":"This transaction has been approved."}],"transHashSha2":"2E6533BDC93C975EE3C1134B7421A337D5B8FB9C257437DB8B4XXXX4BCD92024B33704B811C69E58527359CA8628E8E33E55AA68B881E6F3D15B5F2FEAEB490B","SupplementalDataQualificationIndicator":0,"networkTransId":"HLH5UGDQFZ98LHRLDGIZEG7"},"messages":{"resultCode":"Ok","message":[{"code":"I00001","text":"Successful."}]}}"
console.log('API', res);
var obj = eval("(" + res.response + ")");
console.log(obj);
I solve the problem so I thought I should have to post answers it may be helpful to others.
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);
I know there are several threads on this subject but I've looked through over 30 threads without success.
I have managed to parse a JSON response so it looks like this:
{
"1": {
"id": "1",
"name": "Fruit",
.
.
.
"entities": {
"1": {
"id": "1",
"name": "blue bird",
.
.
.
"status": "1"
},
"2": {
using this code
let json = JSON.parse(body);
console.log(json);
Now I want to access the "id", "name" etc. AND the "id" and "name" for the "entities" tag.
So far I have tried:
console.log(json[0]);
console.log(json.id);
which both returns undefined
I have also tried
console.log(json[0].id);
which gives an error
Any ideas?
In this instance, your first key is 1, so you can access it with json[1].
const json = {
"1": {
"id": "1",
"name": "Fruit"
},
"2": {
"id": "2",
"name": "Veggies"
}
};
console.log(json[1]);
In this json, you can reach the id by
json.1.id
But I think that first of all your json is not correctly written, you should have something like
{
"elements": [
{ "id" : 1, "name" : "fruit" },
{ "id" : 2, "name" : "vegetable" }
]
}
like that, json.elements is a collection/array, and you can loop, count, or any other things you will not be able to do because your json looks like a super heavy list of different properties ( he doesn't know that json.1 and json.2 are the same type of objects.
const jsonData = JSON.parse(body);
for (const i in jsonData) {
for (const j in jsonData[i]) {
console.log('${i}: ${jsonData[i][j]}');
}
}
I've fetched an API and got a JSON object that I need to filter through and store in a new local json file.
the results get returned, but I can't figure out a way to filter through the json file (data) and correctly write it into the new newfile.json file.
.then(
json => {
const data = JSON.stringify(json)
const filtered = data.map( //some filter function )
fs.writeFile('src/data/newfile.json', filtered, 'utf8', function (err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
});
Here is the example of the json data I'm getting from the array of surveys.
{
"surveyId": 515315,
"reviewId": "34152",
"transactionInfo": {
"transactionRef": "1806001511991",
"transactionCity": "Plymouth",
"transactionState": "MN",
"transactionType": null,
"customerFirstName": "Kristine",
},
"serviceProviderInfo": {
"serviceProviderName": "Lobster",
"serviceProviderEmail": "lobster#bayeq.com",
"serviceProviderId": 43346,
"serviceProviderOfficeName": "Oakdale - 30152501",
"serviceProviderRegionName": "Minnesota - Chacich",
"serviceProviderOfficeId": 721581,
"serviceProviderRegionId": 151563
},
"review": {
"source": "encompass",
"rating": "5.0",
"summary": null,
"description": "He was fantastic ",
"agreedToShare": true,
"verifiedCustomer": true,
"retakeSurvey": false,
"surveyResponses": [
{
"question": "How would you rate the service and support you received?",
"type": "Numeric",
"answer": "5"
},
{
"question": "Please rate the level of advice and communication you received from [name].",
"type": "Numeric",
"answer": "5"
},
{
"question": "How likely are you to refer friends and family to [name]?",
"type": "Numeric",
"answer": "10"
},
{
"question": "How would you rate your overall experience?",
"type": "Experience",
"answer": "Great"
}
],
"reportedAbusive": false
},
"reviewStatus": "completed"
}
How do I filter through this and create a new JSON file with the structure like
{
"email": "foo#bar.com",
"rating": 4.56,
"testimonials": [{
"description": "Fugiat ut sed occaecat.",
"firstname": "Bob",
"city": "Bananatown",
"state": "TH"
}]
}
Here I used jquery
var datat = {
"surveyId": 515315,
"reviewId": "34152",
"transactionInfo": {
"transactionRef": "1806001511991",
"transactionCity": "Plymouth",
"transactionState": "MN",
"transactionType": null,
"customerFirstName": "Kristine",
},
"serviceProviderInfo": {
"serviceProviderName": "Lobster",
"serviceProviderEmail": "lobster#bayeq.com",
"serviceProviderId": 43346,
"serviceProviderOfficeName": "Oakdale - 30152501",
"serviceProviderRegionName": "Minnesota - Chacich",
"serviceProviderOfficeId": 721581,
"serviceProviderRegionId": 151563
},
"review": {
"source": "encompass",
"rating": "5.0",
"summary": null,
"description": "He was fantastic ",
"agreedToShare": true,
"verifiedCustomer": true,
"retakeSurvey": false,
"surveyResponses": [
{
"question": "How would you rate the service and support you received?",
"type": "Numeric",
"answer": "5"
},
{
"question": "Please rate the level of advice and communication you received from [name].",
"type": "Numeric",
"answer": "5"
},
{
"question": "How likely are you to refer friends and family to [name]?",
"type": "Numeric",
"answer": "10"
},
{
"question": "How would you rate your overall experience?",
"type": "Experience",
"answer": "Great"
}
],
"reportedAbusive": false
},
"reviewStatus": "completed"
};
datat.review.surveyResponses = datat.review.surveyResponses.filter(function (a) {
return a.answer === "10";
});
var sd = datat.review.surveyResponses[0].question;
alert(sd);
I'm making some guesses here. As has been pointed out, there are so many discrepancies between the sample input and sample output that readers don't have confidence in the mapping inferences that are available. The correlations I've relied upon are inconsistent with the structure of the sample output, but these are the only options that are even plausible.
Also, I think you probably don't want to stringify the incoming data. You want it to be an object, so you can directly address the data; if the data is coming in as a string, you need to parse it into an object with JSON.parse
Here's something that might work. I've chained .then calls to make it easier to insert new steps and reorder them if necessary. I've omitted any error handling, but if you're parsing strings that you receive from the internet, you'll want to have something that can handle the error that will be thrown when the input string isn't valid JSON.
.then(string => JSON.parse(string)) // only needed if your earlier promise returns a string
.then(json => ({
email: json.serviceProviderInfo.serviceProviderEmail,
rating: json.review.rating,
testimonials: [{
description: json.review.description,
firstname: json.transactionInfo.customerFirstName,
city: json.transactionInfo.transactionCity,
state: json.transactionInfo.transactionState
}]
}))
.then(summary => {
return fs.writeFile('src/data/newfile.json', JSON.stringify(summary), 'utf8', function (err) {
if (err) {
return console.log(err);
}
console.log("The file was saved!");
return true
})
})
I wrote a quick script to parse two fairly large json file (~17k records) to do a comparison of the two. I have confirmed they are both valid json (via jsonlintpro) and the same format. (The source is the same so this should be a given. But, I always assume the mistake is mine. And I still do. Just somewhere else.) However, the parsed file just outputs [object, Object]. I'm wondering what the cause could possibly be?
The json format is like this small snippet (anonymized of course):
[
{
"id": "1234",
"name": "Name1",
"url": "https://localhost/Name1",
"date_created": "2013-07-05T18:47:05Z",
"date_cancelled": "",
"props": [
{
"id": "54321",
"type": "Client",
"value": "General Store"
},
{
"id": "65432",
"type": "Contact_Name",
"value": "Joe Smith"
}
]
},
{
"id": "23456",
"name": "Name2",
"url": "https://localhost/Name2",
"date_created": "2014-02-27T17:46:43Z",
"date_cancelled": "",
"props": [
{
"id": "34567",
"type": "Client",
"value": "Bait Shop"
}
]
}]
And here is the pertinent code:
var _ = require('underscore');
var recs = require('./prod.json');
printArr(recs);
console.log(recs.length);
function printArr(arr) {
arr.forEach(function(item) {
console.log(item + ", ");
});
}
Any guidance would be greatly appreciated.
UPDATE:
Ok, so apparently the issue is with my printArr function. I'm not sure what I'm doing wrong there. I'd like to figure it out because I want to expand upon that so I can print selectively.
the parsed file just outputs [object, Object].
This is the expected behavior BECAUSE you are concatenating an object with a string.
Try console.log(item) instead
console.log(item); should indeed print [object, Object], did you try to output its properties instead?
function printArr(arr) {
arr.forEach(function(item) {
console.log( item.id, item.name, item.url, item.date_created, item.date_cancelled, item.props, ';');
});
}
Just export the value from the prod.json file.
prod.json file
module.exports = [
{
"id": "1234",
"name": "Name1"
},
{
"id": "1234",
"name": "Name1"
}]
elsewhere
var recs = require('./prod.json')
console.log(recs)