How to get whole okhttp3 json response and print data? - javascript

I'm trying to get account information from site. I am not sure even how to do that. Am using okhttp3.
I would like to retrieve the whole json object and print it out to see the data. I'd liek to see the whole object first but also retrieve only pieces too.
am told to make use GET using this
app.get("/account", async (req, res) => {
console.log(">>>Retrieving");
const account = await stripe.accounts.retrieve(
'acct_1234'
);
});
Then should get object like this
{
"id": "acct_1234",
"object": "account",
"business_profile": {
"mcc": null,
"name": null,
"product_description": null,
"support_address": null,
"support_email": null,
"support_phone": null,
"support_url": null,
"url": null
},
"business_type": null,
"capabilities": {
"card_payments": "active",
"transfers": "active"
},
"charges_enabled": false,
"country": "CA",
"created": 1599337777,
"default_currency": "cad",
"details_submitted": false,
"email": "email#gmail.com",
"external_accounts": {
"object": "list",
"data": [],
"has_more": false,
"url": "/v1/accounts/acct_1234/external_accounts"
},
"metadata": {},
"payouts_enabled": false,
"requirements": {
"current_deadline": null,
"currently_due": [
"business_profile.product_description",
"business_profile.support_phone",
"business_profile.url",
"external_account",
"tos_acceptance.date",
"tos_acceptance.ip"
],
"disabled_reason": "requirements.past_due",
"errors": [],
"eventually_due": [
"business_profile.product_description",
"business_profile.support_phone",
"business_profile.url",
"external_account",
"tos_acceptance.date",
"tos_acceptance.ip"
],
"past_due": [],
"pending_verification": []
},
"settings": {
"bacs_debit_payments": {},
"branding": {
"icon": null,
"logo": null,
"primary_color": null,
"secondary_color": null
},
"card_payments": {
"decline_on": {
"avs_failure": false,
"cvc_failure": true
},
"statement_descriptor_prefix": null
},
"dashboard": {
"display_name": null,
"timezone": "America/Toronto"
},
"payments": {
"statement_descriptor": "",
"statement_descriptor_kana": null,
"statement_descriptor_kanji": null
},
"payouts": {
"debit_negative_balances": true,
"schedule": {
"delay_days": 7,
"interval": "daily"
},
"statement_descriptor": null
}
},
"tos_acceptance": {
"date": null,
"ip": null,
"user_agent": null
},
"type": "custom"
}
Am using Stripe Api here >>>https://stripe.com/docs/api/accounts/create
I've looked around but am not really understanding, am pretty new at using nodejs and okhttp3. Any advice helps. Thank you

I figured it all out. First i had to change the nodejs to\
app.get("/account", async (req, res) => {
console.log(">>>Retrieving");
res.json(await stripe.accounts.retrieve(
'acct_1234'
));
});
And the http request to display all the data and specific values
public void sendGetRequest(String url){
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.connectTimeout(30, TimeUnit.SECONDS);
builder.readTimeout(30, TimeUnit.SECONDS);
builder.writeTimeout(30, TimeUnit.SECONDS);
httpClient = builder.build();
Request request = new Request.Builder().url(url).build();
try (Response response = httpClient.newCall(request).execute()) {
String responseBody = response.body().string();
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String perfectJSON = gson.toJson(JsonParser.parseString(responseBody));
JSONObject json = new JSONObject(perfectJSON);
JSONObject business = json.getJSONObject("business_profile");
String phone = business.getString("support_phone");
String id = json.getString("id");
this.displayAlert(id+" > "+phone,perfectJSON);
}catch (Exception e){
e.printStackTrace();
}
}

Related

RemoteMessage on flutter from nodejs, data is gone

i have listening message from my nodejs and **vuejs (vue 2) ** to my flutter .
my engine
"firebase-admin": "^11.0.0", // nodejs
"firebase": "^8.2.10", // vuejs ( vue 2 )
// dependencies of my flutter project
firebase_analytics: ^9.1.7
firebase_core: ^1.16.0
firebase_crashlytics: ^2.7.2
firebase_messaging: ^12.0.1
here is my nodejs do
// sentToTopic from js
await admin
.messaging()
.sendToTopic(`${topic}`, message_notification, options)
message_notification: {
title: title,
body: headLine,
url: req.body.url,
other: 'other data',
tag: req.body.tag,
action: req.body.action,
screen_re_fetch: `${req.body.screen_re_fetch}`
}
here is printed on my vueJS when listening to firebase
"data":
"gcm.notification.action": (...)
"gcm.notification.other": (...)
"gcm.notification.screen_re_fetch": (...)
"gcm.notification.url": (...)
"fcmMessageId": (...)
"from": (...)
"notification": Object
"body": (...)
"tag": (...)
"title": (...)
firebase.messaging().onMessage((payload) => { ...
then here is my RemoteMessage on flutter that use toMap() on listening .
// retrieve on flutter (toMap()) ( RemoteMessage ) || firebaseMessage
{
"senderId": null,
"category": null,
"collapseKey": "com.x.xx",
"contentAvailable": false,
"data": {}, // here is my question how i can retrieve the gcm.blabla , where is the data ?
"from": "/topics/x_test",
"messageId": "01675065821511474%802ed552802ed552",
"messageType": null,
"mutableContent": false,
"notification": {
"title": "xxxx",
"titleLocArgs": [],
"titleLocKey": null,
"body": "( COBA PARSING )",
"bodyLocArgs": [],
"bodyLocKey": null,
"android": {
"channelId": null,
"clickAction": null,
"color": null,
"count": null,
"imageUrl": null,
"link": null,
"priority": 0,
"smallIcon": null,
"sound": null,
"ticker": null,
"tag": "river_route",
"visibility": 0
},
"apple": null,
"web": null
},
"sentTime": 1675065820895,
"threadId": null,
"ttl": 86400
}
"data": {}, // here is my question how i can retrieve the gcm.blabla , where is the data ? , am i missing on backend or .... what ?
in my mobile i looking for these data
"gcm.notification.action": (...)
"gcm.notification.other": (...)
"gcm.notification.screen_re_fetch": (...)
"gcm.notification.url": (...)
i need the action thats logic todo ( web ) alr implemented and in mobile is ongoing .
anyone else have same problem ?

Why are asset attributes missing from Imgix Management API?

I am querying the Imgix Management API with no issue. I can retrieve an individual asset and a list of assets. However, most of the data properties are null. It looks like this:
{
"data": {
"attributes": {
"analyzed_content_warnings": null,
"analyzed_faces": null,
"analyzed_tags": null,
"categories": null,
"color_model": null,
"color_profile": null,
"colors": null,
"content_type": "image/jpeg",
"custom_fields": null,
"date_created": 1667935028,
"date_modified": null,
"description": null,
"dpi_height": null,
"dpi_width": null,
"face_count": null,
"file_size": 1016205,
"has_frames": null,
"media_height": null,
"media_kind": "IMAGE",
"media_width": null,
"name": null,
"origin_path": "/test/roses.jpeg",
"source_id": "XXXXXXXXXXXXXXXXXXXX",
"tags": null,
"uploaded_by": null,
"uploaded_by_api": false,
"warning_adult": null,
"warning_medical": null,
"warning_racy": null,
"warning_spoof": null,
"warning_violence": null
},
"id": "XXXXXXXXXXXXXXXXXXX/test/roses.jpeg",
"type": "assets"
},
"included": [],
"jsonapi": {
"version": "1.0"
},
"meta": {
"authentication": {
"authorized": true,
"clientId": null,
"mode": "PUBLIC_APIKEY",
"modeTitle": "Public API Key",
"tag": "XXXXXXXXXXXXXXX",
"user": null
},
"server": {
"commit": "7c78ee15",
"status": {
"healthy": true,
"read_only": false,
"tombstone": false
},
"version": "3.187.0"
}
}
}
I'm missing data.colors, data.media_height, data.media_width.
My code is very basic:
import fetch from 'node-fetch'
const imgix_key = 'xxxxxxxx'
const imgix_source_id = 'xxxxxxxx'
const imgix_url = `https://api.imgix.com/api/v1/assets/${imgix_source_id}/test/roses.jpeg`
async function init() {
const method = 'get'
const headers = {
Authorization: `Bearer ${imgix_key}`,
'Content-Type': 'application/x-www-form-urlencoded',
}
const response = await fetch(imgix_url, { headers, method })
const body = await response.text()
console.log(body)
}
init()
I can access data.colors if I request this image from the rendering API with the palette=json parameter, so I know the property theoretically exists.
Request to https://xxxxxxx.imgix.net/test/roses.jpeg?palette=json:
{
"colors":[
{
"red":0.960784,
"hex":"#f5ece9",
"blue":0.913725,
"green":0.92549
},
{
"red":0.843137,
"hex":"#d7cb99",
"blue":0.6,
"green":0.796078
},
{
"red":0.768627,
"hex":"#c44535",
"blue":0.207843,
"green":0.270588
},
{
"red":0.670588,
"hex":"#aba544",
"blue":0.266667,
"green":0.647059
},
{
"red":0.454902,
"hex":"#746a4f",
"blue":0.309804,
"green":0.415686
},
{
"red":0.227451,
"hex":"#3a452f",
"blue":0.184314,
"green":0.270588
}
],
"average_luminance":0.387471,
"dominant_colors":{
"vibrant":{
"red":0.698039,
"hex":"#b2524d",
"blue":0.301961,
"green":0.321569
},
"muted_light":{
"red":0.823529,
"hex":"#d2b3aa",
"blue":0.666667,
"green":0.701961
},
"muted":{
"red":0.698039,
"hex":"#b2524d",
"blue":0.301961,
"green":0.321569
},
"vibrant_dark":{
"red":0.368627,
"hex":"#5e220c",
"blue":0.0470588,
"green":0.133333
},
"vibrant_light":{
"red":0.898039,
"hex":"#e5c699",
"blue":0.6,
"green":0.776471
},
"muted_dark":{
"red":0.305882,
"hex":"#4e3529",
"blue":0.160784,
"green":0.207843
}
}
}
I've tried adding a fields parameter, like this:
https://api.imgix.com/api/v1/assets/xxxxxxxxxxxxxx/test/roses.jpeg?fields[assets]=name,origin_path,colors,media_width,media_height
I get the specified properties, but they're still null.
Could anyone help me understand why these properties are coming back null?
I would like to write a prebuild script to cache the image metadata so I can set image dimensions and colorful placeholder blocks.
Thanks
I would encourage you to write into our support team (support#imgix.com) with this issue. The reason these fields return null is likely tied to your account/Source settings, which they can help you navigate. Hope that helps.

Yii2 and Ajax: The response is not the SQL query results

I want to execute a AJAX query using jQuery but the response is not what I want.
Client side:
$.ajax({
url: "/family?idperson=1234",
dataType: 'json',
success: function(res) {
console.log(JSON.stringify(res, null, 4));
},
error: function(err) {
}
});
Server side:
public function actionFamily($idperson)
{
$searchModelFamily = new FamilySearch();
$dataProvider = $searchModelFamily->searchByIdperson(Yii::$app->request->queryParams, $idperson); // This database query works great.
Yii::$app->response->format = Response::FORMAT_JSON;
return $dataProvider;
}
This is the content of the JSON object: It seems to a some parts of the SQL query. But I need the SQL results.
{
"query": {
"sql": null,
"on": null,
"joinWith": null,
"select": null,
"selectOption": null,
"distinct": null,
"from": null,
"groupBy": null,
"join": null,
"having": null,
"union": null,
"params": [],
"where": {
"idperson": "1234"
},
"limit": null,
"offset": null,
"orderBy": null,
"indexBy": null,
"emulateExecution": false,
"modelClass": "app\\models\\Family",
"with": null,
"asArray": null,
"multiple": null,
"primaryModel": null,
"link": null,
"via": null,
"inverseOf": null
},
"key": null,
"db": null,
"id": null
}
It seems like your method actionFamily returns the DataProvider object rather then the data you want it to fetch. If actionFamily is a method within a yii\rest\controller it should work, but my guess is that you are using a regular yii\web\controller that will just return the object as it is.
To get the data of the DataProvider, try changing this...
return $dataProvider;
into this...
return $dataProvider->getModels();
or change the controller class (if it is a REST feature) as discussed above.

How to loop through JSON array in nodejs?

I'm trying to read value from json array to display in the page. I have tried with below code but couldn't make it. I was trying long time to get this done and Please advise what am I doing wrong here.
Also I'm not able to do JSON.parse- unexpected input error.
http.request(options, function(res) {
res.on('data', function (result) {
console.log(result);//Displaying below format of result without any error
console.log(result.Reference[0].name); Error //TypeError: Cannot read property '0' of undefined.
console.log(result.Reference.length);//Error TypeError: Cannot read property 'length' of undefined
JSON format: when printing result
{
"Reference": [
{
"name": "xxxxxxxx",
"typeReference": {
"articulation": 0,
"locked": false,
"createdBy": {
"userName": "System",
},
"lastModifiedBy": {
"userName": "System",
},
"lastModified": 1391084398660,
"createdOn": 1391084398647,
"isSystem": true
},
"communityReference": {
"name": "xxxxxx",
"language": "English",
"sbvr": false,
"parentReference": {
"name": "xxxxx",
"sbvr": false,
"meta": false,
"parentReference": null,
"locked": false,
"createdBy": {
"userName": "xxxxx",
},
"lastModifiedBy": {
"userName": "xxxxx",
},
"lastModified": 1459185726230,
"createdOn": 1456337723119,
"isSystem": false
},
"locked": false,
"createdBy": {
"userName": "xxxxx",
},
"lastModifiedBy": {
"userName": "xxxxxx",
},
"lastModified": 1472655031590,
"createdOn": 1472654988012,
"isSystem": false
},
"locked": false,
"createdBy": {
"userName": "xxxxx",
},
"lastModifiedBy": {
"userName": "xxxxx",
"firstName": "xxxxx",
},
"lastModified": 1473171981520,
"createdOn": 1472655253366,
"isSystem": false
},
{
"name":"yyyyyy", same attribute type as above.
...
},
{
..
},
res is a stream, and the data event indicates that it has received some data, but it may or may not be all the data. You're not likely to get all the data at once, so you need to wait until the end event fires, when you have the whole JSON object:
var json = '';
res.on('data', function ( chunk ) {
json += chunk;
} );
res.on('end', function ( ) {
var result = JSON.parse( json );
console.log( result.Reference[0].name );
} );
or you can use json-stream which can read in JSON chunk by chunk and handle that correctly, unlike JSON.parse.
However, I recommend that you don't use either of the above solutions and instead use request, which greatly simplifies this and other aspects of making HTTP requests and handling the response.
You can try this with some additional and safe validations:
{
if ( result ) {
var data = (typeof result == "string") ? JSON.parse(result) : result;
if (data.hasOwnProperty("Reference")) {
for(var i = 0; i < data.Reference.length; i++; ) {
try {
var reference = data.Reference[i];
console.log("Name:" + reference.name);
//Your app logic
} catch(e) {
//In case if any invalid references, then continue with others
console.warn("Error processing reference - " + e);
}
}
} else {
console.warn("No References were found!");
}
} else {
console.error("Invalid JSON!");
}
}
Hope it helps!

How do I expand nested relationships in REST API using Sails.js

I am a newbie to NodeJS and Sails.js.
I want create a REST API that allows me to expand a resource based on query parameter. For eg
HTTP GET /snippets
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"url": "http://localhost:8000/snippets/1/",
"highlight": "htep://localhost:8000/snippets/1/highlight/",
"title": "test",
"code": "def test():\r\n pass",
"linenos": false,
"language": "Clipper",
"style": "autumn",
"owner": "http://localhost:8000/users/2/",
"extra": "http://localhost:8000/snippetextras/1/"
}
]}
HTTP GET /snippets?expand=owner
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"url": "http://localhost:8000/snippets/1/",
"highlight": "http://localhost:8000/snippets/1/highlight/",
"title": "test",
"code": "def test():\r\n pass",
"linenos": false,
"language": "Clipper",
"style": "autumn",
"owner": {
"url": "http://localhost:8000/users/2/",
"username": "test",
"email": "test#test.com"
},
"extra": "http://localhost:8000/snippetextras/1/"
}
]}
Wondering how can I do that in Sails.js or NodeJS?
You should use assocations.
Here is how you would create a one-to-many association between your User model and your Snippet model:
// User.js
module.exports = {
// ...
attributes: {
// ...
snippets: {
collection: 'Snippet',
via: 'owner'
}
}
};
// Snippet.js
module.exports = {
// ...
attributes: {
// ...
owner: {
model: 'User'
}
}
};
Then you can hit /snippets if you want a list of snippets, and hit /snippets?populate=[owner] if you need details about the owners of the snippets.

Categories