Related
I'm trying to better understand how to work with nested JSON objects in JavaScript/React.
I am getting data through the GitLab API in the following form:
const merge_requests = [
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "tes.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},]
I want to loop through all objects(merge requests) in this JSON and create a new array with the merge_user.name.
console.log(merge_requests[0].merge_user.name);
console.log(merge_requests[1].merge_user.name);
The logs above return both the correct values. However, I cannot loop through the JSON to create a new array from the data like this:
const arrTest = [];
for(var i = 0; i < Object.keys(merge_requests).length; i++)
{
var mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
}
The code above leads to the following error: Uncaught (in promise) TypeError: resultData[i].merge_user is null
Here is a picture:
I am currently learning JS coming from R. I have huge problems working with JSON instead of dataframes and I cannot find any documentation to learn from. I would appreciated any advice/ sources.
const arrTest = [];
for(var i = 0; i < merge_requests.length; i++){
let mergeUserName = merge_requests[i].merge_user?.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
merge_requests[i].merge_user?.name will return undefined if object is not present in the json.
There is no need to use Object.keys(),you can use merge_requests.length directly
const arrTest = [];
for(var i = 0; i < merge_requests.length; i++){
let mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
const merge_requests = [
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "tes.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
}]
const arrTest = [];
for(var i = 0; i < merge_requests.length; i++){
let mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
I copy & pasted your code & JSON and it works fine.
Make sure your JSON is parsed after getting it from ate API typeof merge_requests should return object, if it returns string then do the following:
const parsedData = JSON.parse(merge_requests) and loop through parsedData
i checked your code it's working fine.
Check your api request, are you sure you waiting for it till it get fulfilled?
hi im building application and i need to store data in txt file and retrieve it
the data is object like this .. .
[
{
"key": 0,
"id": 1,
"number": "1001",
"name": "سلعة ملموسة",
"offer_end_date": null,
"offer_start_date": null,
"components": [],
"quantity": "9",
"product": {
"id": 1,
"name": "سلعة ملموسة",
"number": "1001",
"product_id": null,
"foreign_name": "Product",
"can_be_sold": 1,
"can_be_purchased": 1,
"can_be_rented": 1,
"available_on_pos": 1,
"pos_quick_lunch": 1,
"available_on_manufacture": 1,
"product_category_id": 1,
"product_unit_type_id": null,
"location_id": null,
"area_id": null,
"discount_value": 10,
"balance": null,
"smallest_unit_id": 1,
"smallest_unit_barcode": null,
"smallest_unit_selling_price": 10,
"smallest_unit_cost": null,
"smallest_unit_selling_price_above": null,
"smallest_unit_selling_price_above_price": null,
"tax_value": 16,
"state_id": 1,
"warehouse_id": null,
"product_type_id": 1,
"product_policy_id": null,
"tax_user_id": null,
"user_id": null,
"get_specification_on_lines": null,
"is_products_has_expire_date": 1,
"is_products_has_patch_number": 1,
"is_products_has_serial_number": 1,
"offer_end_date": null,
"offer_start_date": null,
"last_purchase_date": null,
"last_purchase_purchase": null,
"last_purchase_price": null,
"last_purchase_discount": null,
"created_by": null,
"deleted_by": null,
"approved_by": null,
"approved_date": null,
"approved_state_id": null,
"note": null,
"created_at": "2022-03-04T06:52:16.000000Z",
"updated_at": "2022-03-04T06:52:16.000000Z",
"deleted_at": null,
"get_pos_product_componentss": [],
"get_pos_product_components": [],
"get_smallest_unit_id": {
"id": 1,
"name": "حبة",
"foreign_name": "unit",
"number": "1",
"created_by": 1,
"deleted_by": null,
"approved_by": null,
"approved_date": null,
"approved_state_id": null,
"note": null,
"created_at": "2022-03-04T06:52:15.000000Z",
"updated_at": "2022-03-04T06:52:15.000000Z",
"deleted_at": null
},
"get_product_offers": []
},
"smallest_unit_selling_price": 10,
"smallest_unit_selling_price_above": null,
"smallest_unit_selling_price_above_price": null,
"discount": 0,
"allowed_discount": 10,
"tax_value": 16,
"unit": "حبة",
"smallest_unit_id": 1,
"note": null,
"active": 1,
"price": 104.39999999999999
}
]
now this object i need to store it in file called text.txt
how can i store the object inside the file ..
and how can i retrieve the data using JavaScript ..
thanks ..
ive found solutions thats i can put the object in cookies but my problem with cookies they only allowing 4kb of data
never mind i found this solution ..
first of store data in localStorage like this ..
localStorage.setItem("orders", JSON.stringify(this.orders));
then access it like this ..
var orders = JSON.parse(localStorage.getItem('orders'));
console.log(orders);
Is it possible to get the Braintree fee amount while searching for transactions using Transaction.search() method? I specifically use
Braintree Node.js SDK API, so when I call the method:
const gateway = braintree.connect({
environment: braintree.Environment.Production,
merchantId : process.env.BRAINTREE_merchantId,
publicKey : process.env.BRAINTREE_publicKey,
privateKey : process.env.BRAINTREE_privateKey,
});
// start and end are well formatted dates, irrelevant here
const stream = gateway.transaction.search((search) => {
search.createdAt().between(start, end)
});
let result = [];
stream.on("data", (transaction) => {
result.push(transaction);
});
stream.on("end", () => {
console.log(result[0]);
});
stream.on("error", reject);
stream.resume();
My console.log(result[0]) shows pretty big (160 lines of code) single transaction object, where transaction.serviceFeeAmount: null.
console.log({
"id": "1egncjr5",
"status": "settled",
"type": "sale",
"currencyIsoCode": "EUR",
"amount": "799.00",
"merchantAccountId": "mycompanyEUR",
"subMerchantAccountId": null,
"masterMerchantAccountId": null,
"orderId": "54144",
"createdAt": "2018-03-07T08:55:09Z",
"updatedAt": "2018-03-07T19:41:10Z",
"customer": {
"id": null,
"firstName": null,
"lastName": null,
"company": "Kunlabora NV",
"email": "client#email.com",
"website": null,
"phone": null,
"fax": null
},
"billing": {
"id": null,
"firstName": null,
"lastName": null,
"company": "Kunlabora NV",
"streetAddress": "Veldkant 33 A",
"extendedAddress": null,
"locality": "Kontich",
"region": null,
"postalCode": "2550",
"countryName": "Belgium",
"countryCodeAlpha2": "BE",
"countryCodeAlpha3": "BEL",
"countryCodeNumeric": "056"
},
"refundId": null,
"refundIds": [],
"refundedTransactionId": null,
"partialSettlementTransactionIds": [],
"authorizedTransactionId": null,
"settlementBatchId": "2018-03-08_mycompanyEUR_ecwhvhcf",
"shipping": {
"id": null,
"firstName": null,
"lastName": null,
"company": null,
"streetAddress": null,
"extendedAddress": null,
"locality": null,
"region": null,
"postalCode": null,
"countryName": null,
"countryCodeAlpha2": null,
"countryCodeAlpha3": null,
"countryCodeNumeric": null
},
"customFields": "",
"avsErrorResponseCode": null,
"avsPostalCodeResponseCode": "U",
"avsStreetAddressResponseCode": "U",
"cvvResponseCode": "M",
"gatewayRejectionReason": null,
"processorAuthorizationCode": "735709",
"processorResponseCode": "1000",
"processorResponseText": "Approved",
"additionalProcessorResponse": null,
"voiceReferralNumber": "",
"purchaseOrderNumber": null,
"taxAmount": "0.00",
"taxExempt": false,
"creditCard": {
"token": null,
"bin": "CENSORED",
"last4": "CENSODER",
"cardType": "MasterCard",
"expirationMonth": "CENSORED",
"expirationYear": "CENSORED",
"customerLocation": "CENSORED",
"cardholderName": "",
"imageUrl": "https://assets.braintreegateway.com/payment_method_logo/mastercard.png?environment=production",
"prepaid": "No",
"healthcare": "No",
"debit": "No",
"durbinRegulated": "No",
"commercial": "No",
"payroll": "No",
"issuingBank": "BNP PARIBAS FORTIS",
"countryOfIssuance": "BEL",
"productId": "MCB",
"uniqueNumberIdentifier": null,
"venmoSdk": false,
"maskedNumber": "CENSORED",
"expirationDate": "04/2020"
},
"statusHistory": [
{
"timestamp": "2018-03-07T08:55:10Z",
"status": "authorized",
"amount": "799.00",
"user": "office#mycompany.com",
"transactionSource": "api"
},
{
"timestamp": "2018-03-07T08:55:10Z",
"status": "submitted_for_settlement",
"amount": "799.00",
"user": "office#mycompany.com",
"transactionSource": "api"
},
{
"timestamp": "2018-03-07T19:41:10Z",
"status": "settled",
"amount": "799.00",
"user": null,
"transactionSource": ""
}
],
"planId": null,
"subscriptionId": null,
"subscription": {
"billingPeriodEndDate": null,
"billingPeriodStartDate": null
},
"addOns": [],
"discounts": [],
"descriptor": {
"name": null,
"phone": null,
"url": null
},
"recurring": false,
"channel": "woocommerce_bt",
"serviceFeeAmount": null,
"escrowStatus": null,
"disbursementDetails": {
"disbursementDate": null,
"settlementAmount": null,
"settlementCurrencyIsoCode": null,
"settlementCurrencyExchangeRate": null,
"fundsHeld": null,
"success": null
},
"disputes": [],
"authorizationAdjustments": [],
"paymentInstrumentType": "credit_card",
"processorSettlementResponseCode": "",
"processorSettlementResponseText": "",
"threeDSecureInfo": null,
"shipsFromPostalCode": null,
"shippingAmount": null,
"discountAmount": null,
"paypalAccount": {},
"coinbaseAccount": {},
"applePayCard": {},
"androidPayCard": {},
"visaCheckoutCard": {},
"masterpassCard": {}
})
Question: How do I get the transaction fee here?
You might find it in transactionFeeAmount field
This is the answer I received from Braintree support team:
Unfortunately no it is not possible to search for the Braintree fee amount using the API at this time (meaning 14/05/2018).
You can calculate the fees for individual transactions by performing an Advanced Transaction Search.
Log into the Control Panel
Under Advanced Search, click Transactions
Uncheck the box next to Creation date range
Check the box next to Disbursed date range
Choose your desired date range
Click Search
On the results page, click Download
Open the CSV file in the spreadsheet program of your choice
From here, you can create additional columns for your transaction fees. To find your specific transaction fees, look at the Pricing Schedule on your statement. Make sure to round down, and then apply the fees to your individual transactions.
So it looks like I am going to implement some PhantomJS module to do just that.
How can you parse out all the values for a particular data point within a complex json response form a rest service call?
Here is my JQUERY code to get the rest service json response. I am looking to get all occurrences of "Id" for all "Approver" elements found in the json data and add them to delimited list - preferably using a
;
to separate each "Id"
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script><script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'GET',
url: 'MySite/Change/Request/12345/Approvals/GetApprovalGroupUsers?changeNumber=98765',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.Id
}));
});
}
});
});
});
</script>
</head>
<body>
<button>Click me to get listing of Id's</button>
</body>
</html>
The json data from the service in such:
{
"ApprovalSession": "3ebd4e73-7fc5-4113-9ccd-18833318ee09",
"LoadStatus": 0,
"Index": 0,
"ApprovalId": 0,
"Type": null,
"Approver": null,
"ApproverDisplay": null,
"Status": null,
"CreatedBy": null,
"CanBeRemoved": false,
"ConfigurationItems": [
"cigs01e4a002( OPERATING SYSTEM )",
"cigs01e4a002( OPERATING SYSTEM )",
"cigs01e4a004( OPERATING SYSTEM )",
"cigs01e4a004( OPERATING SYSTEM )"
],
"ApprovalReasons": [
{
"AssociatedCI": "abc4a002( OPERATING SYSTEM )",
"AssociatedRuleName": "Default Impact",
"AssociatedRuleApprovalType": null,
"AssociatedRulePartyType": "Targeted Group",
"AssociatedRulePartyName": "Operational Owner",
"AssociatedAdditionalComment": ""
},
{
"AssociatedCI": "xyza004( OPERATING SYSTEM )",
"AssociatedRuleName": "Default Impact ",
"AssociatedRuleApprovalType": null,
"AssociatedRulePartyType": "Targeted Group",
"AssociatedRulePartyName": "Technical Owner",
"AssociatedAdditionalComment": "Substitute Role"
}
],
"PossibleApprovers": [
{
"Approver": {
"Id": "Vzz436",
"Display": "some name",
"LineOfBusinessCode": "25",
"LineOfBusinessName": "Unix",
"LineOfBusinessHierarchy": null,
"PhoneNumber": "+123456789",
"RoleName": null,
"FullName": null,
"LineOfBusiness": null,
"ErrorMessage": null
},
"IsEscalation": false,
"IsDelegate": false
},
{
"Approver": {
"Id": "ppp71",
"Display": "more names",
"LineOfBusinessCode": "5",
"LineOfBusinessName": "Tech",
"LineOfBusinessHierarchy": null,
"PhoneNumber": "+987654321",
"RoleName": null,
"FullName": null,
"LineOfBusiness": null,
"ErrorMessage": null
},
"IsEscalation": false,
"IsDelegate": false
},
{
"Approver": {
"Id": "aaa5",
"Display": "mickey mouse",
"LineOfBusinessCode": "8",
"LineOfBusinessName": "Digital",
"LineOfBusinessHierarchy": null,
"PhoneNumber": "+87877676665",
"RoleName": null,
"FullName": null,
"LineOfBusiness": null,
"ErrorMessage": null
},
"IsEscalation": false,
"IsDelegate": false
}
],
"OriginalApprovals": [ ],
"AggregatedApproval": null,
"IsAggregated": false,
"AggregationId": 0,
"UpdatedBy": null,
"UpdatedDt": null,
"IsGroupActive": false
}
This is how you can get all ID's of the approvers, delimited by a semi-colon.
var data = {
"ApprovalSession": "3ebd4e73-7fc5-4113-9ccd-18833318ee09",
"LoadStatus": 0,
"Index": 0,
"ApprovalId": 0,
"Type": null,
"Approver": null,
"ApproverDisplay": null,
"Status": null,
"CreatedBy": null,
"CanBeRemoved": false,
"ConfigurationItems": [
"cigs01e4a002( OPERATING SYSTEM )",
"cigs01e4a002( OPERATING SYSTEM )",
"cigs01e4a004( OPERATING SYSTEM )",
"cigs01e4a004( OPERATING SYSTEM )"
],
"ApprovalReasons": [
{
"AssociatedCI": "abc4a002( OPERATING SYSTEM )",
"AssociatedRuleName": "Default Impact",
"AssociatedRuleApprovalType": null,
"AssociatedRulePartyType": "Targeted Group",
"AssociatedRulePartyName": "Operational Owner",
"AssociatedAdditionalComment": ""
},
{
"AssociatedCI": "xyza004( OPERATING SYSTEM )",
"AssociatedRuleName": "Default Impact ",
"AssociatedRuleApprovalType": null,
"AssociatedRulePartyType": "Targeted Group",
"AssociatedRulePartyName": "Technical Owner",
"AssociatedAdditionalComment": "Substitute Role"
}
],
"PossibleApprovers": [
{
"Approver": {
"Id": "Vzz436",
"Display": "some name",
"LineOfBusinessCode": "25",
"LineOfBusinessName": "Unix",
"LineOfBusinessHierarchy": null,
"PhoneNumber": "+123456789",
"RoleName": null,
"FullName": null,
"LineOfBusiness": null,
"ErrorMessage": null
},
"IsEscalation": false,
"IsDelegate": false
},
{
"Approver": {
"Id": "ppp71",
"Display": "more names",
"LineOfBusinessCode": "5",
"LineOfBusinessName": "Tech",
"LineOfBusinessHierarchy": null,
"PhoneNumber": "+987654321",
"RoleName": null,
"FullName": null,
"LineOfBusiness": null,
"ErrorMessage": null
},
"IsEscalation": false,
"IsDelegate": false
},
{
"Approver": {
"Id": "aaa5",
"Display": "mickey mouse",
"LineOfBusinessCode": "8",
"LineOfBusinessName": "Digital",
"LineOfBusinessHierarchy": null,
"PhoneNumber": "+87877676665",
"RoleName": null,
"FullName": null,
"LineOfBusiness": null,
"ErrorMessage": null
},
"IsEscalation": false,
"IsDelegate": false
}
],
"OriginalApprovals": [ ],
"AggregatedApproval": null,
"IsAggregated": false,
"AggregationId": 0,
"UpdatedBy": null,
"UpdatedDt": null,
"IsGroupActive": false
}
data.PossibleApprovers.forEach(function (approver) { document.write(approver.Approver.Id + ';')})
I am using an API that provides the output in JSON format and I am sure about the fields that it contains. I want to deserialize it into a list format.
I went through the Newtonsoft.Json namespace but didn't get much help. The following article was good but it didn't serve my purpose as I am not aware of the key/value pairs.
Article: http://www.newtonsoft.com/json/help/html/deserializeobject.htm
My code:
static void GetShares()
{
WebRequest request = WebRequest.Create("https://shares.ppe.datatransfer.microsoft.com/api/v1/data/shares/");
request.Method = "GET";
request.Headers.Add("Authorization","Basic "+
Convert.ToBase64String(
Encoding.ASCII.GetBytes("useridandpassword")));
request.ContentType = "application/json";
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
}
I have executed your code and it seems that it is returning and printing the following data on console(not in readable format(indented)).
[
{
"browse_count": 0,
"bytes_free_string": null,
"bytes_total_string": null,
"bytes_unknown": true,
"comment_added_at": null,
"content_added_at": null,
"created_at": "2016-06-09T17:23:53-07:00",
"directory": "/",
"error_bytes_free_size": null,
"error_percent_free": null,
"home_share": false,
"id": 63,
"name": "linuxServerRoot",
"node_id": 5,
"percent_free": null,
"status": null,
"status_at": "2016-12-06T21:24:26-08:00",
"status_message": null,
"updated_at": "2016-12-06T21:24:26-08:00",
"warn_bytes_free_size": null,
"warn_percent_free": null
},
{
"browse_count": 6,
"bytes_free_string": null,
"bytes_total_string": null,
"bytes_unknown": true,
"comment_added_at": null,
"content_added_at": null,
"created_at": "2016-10-17T14:52:06-07:00",
"directory": "/Windows_RTM",
"error_bytes_free_size": null,
"error_percent_free": null,
"home_share": false,
"id": 584,
"name": "Windows_RTM1.1",
"node_id": 7,
"percent_free": null,
"status": null,
"status_at": "2016-12-06T21:24:33-08:00",
"status_message": null,
"updated_at": "2016-12-06T21:24:33-08:00",
"warn_bytes_free_size": null,
"warn_percent_free": null
},
{
"browse_count": 3,
"bytes_free_string": null,
"bytes_total_string": null,
"bytes_unknown": true,
"comment_added_at": null,
"content_added_at": null,
"created_at": "2016-11-29T00:40:20-08:00",
"directory": "/Stats_subscription-For-Demo-Do not delete/WUS-Stats_subscription--Default no stats",
"error_bytes_free_size": null,
"error_percent_free": null,
"home_share": false,
"id": 1401,
"name": "WUS-Stats_subscription--Default no stats",
"node_id": 5,
"percent_free": null,
"status": null,
"status_at": "2016-12-06T21:24:27-08:00",
"status_message": null,
"updated_at": "2016-12-06T21:24:27-08:00",
"warn_bytes_free_size": null,
"warn_percent_free": null
},
{
"browse_count": 0,
"bytes_free_string": null,
"bytes_total_string": null,
"bytes_unknown": true,
"comment_added_at": null,
"content_added_at": null,
"created_at": "2016-11-29T01:06:20-08:00",
"directory": "/Stats_subscription-For-Demo-Do not delete/WUS-Stats_subscription-EyeBall",
"error_bytes_free_size": null,
"error_percent_free": null,
"home_share": false,
"id": 1408,
"name": "WUS-Stats_subscription-EyeBall",
"node_id": 5,
"percent_free": null,
"status": null,
"status_at": "2016-12-06T21:24:28-08:00",
"status_message": null,
"updated_at": "2016-12-06T21:24:28-08:00",
"warn_bytes_free_size": null,
"warn_percent_free": null
},
{
"browse_count": 0,
"bytes_free_string": null,
"bytes_total_string": null,
"bytes_unknown": true,
"comment_added_at": null,
"content_added_at": null,
"created_at": "2016-11-29T01:06:50-08:00",
"directory": "/Stats_subscription-For-Demo-Do not delete/WUS-Stats_subscription-Goku",
"error_bytes_free_size": null,
"error_percent_free": null,
"home_share": false,
"id": 1409,
"name": "WUS-Stats_subscription-Goku",
"node_id": 5,
"percent_free": null,
"status": null,
"status_at": "2016-12-06T21:24:29-08:00",
"status_message": null,
"updated_at": "2016-12-06T21:24:29-08:00",
"warn_bytes_free_size": null,
"warn_percent_free": null
},
{
"browse_count": 0,
"bytes_free_string": null,
"bytes_total_string": null,
"bytes_unknown": true,
"comment_added_at": null,
"content_added_at": null,
"created_at": "2016-11-29T01:07:18-08:00",
"directory": "/Stats_subscription-For-Demo-Do not delete/WUS-Stats_subscription-Cybersecurity",
"error_bytes_free_size": null,
"error_percent_free": null,
"home_share": false,
"id": 1410,
"name": "WUS-Stats_subscription-Cybersecurity",
"node_id": 5,
"percent_free": null,
"status": null,
"status_at": "2016-12-06T21:24:30-08:00",
"status_message": null,
"updated_at": "2016-12-06T21:24:30-08:00",
"warn_bytes_free_size": null,
"warn_percent_free": null
},
{
"browse_count": 0,
"bytes_free_string": null,
"bytes_total_string": null,
"bytes_unknown": true,
"comment_added_at": null,
"content_added_at": null,
"created_at": "2016-11-29T01:08:00-08:00",
"directory": "/Stats_subscription-For-Demo-Do not delete/WUS-Stats_subscription-Feature_Phones_Dubai SOR",
"error_bytes_free_size": null,
"error_percent_free": null,
"home_share": false,
"id": 1411,
"name": "WUS-Stats_subscription-Feature_Phones_Dubai SOR",
"node_id": 5,
"percent_free": null,
"status": null,
"status_at": "2016-12-06T21:24:31-08:00",
"status_message": null,
"updated_at": "2016-12-06T21:24:31-08:00",
"warn_bytes_free_size": null,
"warn_percent_free": null
},
{
"browse_count": 0,
"bytes_free_string": null,
"bytes_total_string": null,
"bytes_unknown": true,
"comment_added_at": null,
"content_added_at": null,
"created_at": "2016-11-29T01:10:47-08:00",
"directory": "/Stats_subscription-For-Demo-Do not delete/WUS-Stats_subscription-Nimbus",
"error_bytes_free_size": null,
"error_percent_free": null,
"home_share": false,
"id": 1412,
"name": "WUS-Stats_subscription-Nimbus",
"node_id": 5,
"percent_free": null,
"status": null,
"status_at": "2016-12-06T21:24:32-08:00",
"status_message": null,
"updated_at": "2016-12-06T21:24:32-08:00",
"warn_bytes_free_size": null,
"warn_percent_free": null
},
{
"browse_count": 0,
"bytes_free_string": null,
"bytes_total_string": null,
"bytes_unknown": true,
"comment_added_at": null,
"content_added_at": null,
"created_at": "2016-11-30T15:49:52-08:00",
"directory": "/EPRS-Connect/HK-EPRS-NVIDIA",
"error_bytes_free_size": null,
"error_percent_free": null,
"home_share": false,
"id": 1467,
"name": "HK-EPRS-NVIDIA",
"node_id": 7,
"percent_free": null,
"status": null,
"status_at": "2016-12-06T21:24:34-08:00",
"status_message": null,
"updated_at": "2016-12-06T21:24:34-08:00",
"warn_bytes_free_size": null,
"warn_percent_free": null
}
]
And You asked to deserialize it in readable format. From this statement i think you want to print/show it on the console in readable format.
To achieve this you can make use of Newtonsoft.Jsonlibrary all you have to add the Json.NET nuget package to your project and following code just before the Console.WriteLine(responseFromServer); statement.
JToken jsonToken = JToken.Parse(responseFromServer);
responseFromServer = jsonToken.ToString(Newtonsoft.Json.Formatting.Indented);
This will print / show the JSON on console window in readable format.
This should do it:
WebRequest request = WebRequest.Create("https://shares.ppe.datatransfer.microsoft.com/api/v1/data/shares/");
request.Method = "GET";
request.Headers.Add("Authorization", "Basic " +
Convert.ToBase64String(
Encoding.ASCII.GetBytes("userid:password")));
request.ContentType = "application/json";
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
JArray items = JArray.Parse(responseFromServer);
Console.WriteLine($"{"Keys".PadRight(24)}Values");
Console.WriteLine($"{"".PadRight(50, '-')}");
foreach (JToken token in items)
{
Dictionary<string, string> dictionary = token.ToObject<Dictionary<string, string>>();
int length = 28;
foreach (var property in dictionary)
{
Console.WriteLine($"{property.Key.PadRight(length)}{property.Value}");
}
Console.WriteLine($"----------------------");
}
This parses the payload as a JArray, grabs the first item (check for null first), deserialises it into a dictionary and selects the keys. I picked 24 as it's the longest key length. You could make the padding variable by using this code.