Getting a value from JSON, Node.js - javascript

I am having trouble with getting a value from inside of a JSON file, which has been retrieved from the Steam API (http://steamcommunity.com/dev).
The problem occurs when I attempt to print the data, the Node.js file code is below:
var data = JSON.parse(body); // Stores the JSON data which has been retrieved
console.log(data.result.toString(350462890).market_hash_name); // Attempts to grab the value of the market_hash_name from the JSON data and display it to screen
I get the following response: "undefined".
JSON data used below:
{
"result": {
"350462890": {
"icon_url": "fWFc82js0fmoRAP-qOIPu5THSWqfSmTELLqcUywGkijVjZYMUrsm1j-9xgEObwgfEh_nvjlWhNzZCveCDfIBj98xqodQ2CZknz5-OOqhNQh0fTvSAK5KVPAoywXpDS4n5YliBtazruNQfgrssNfPN-IqYtkdSpTZU_OCYAir70luiaAPfZOIqHznw223bZvDH3kW",
"icon_url_large": "fWFc82js0fmoRAP-qOIPu5THSWqfSmTELLqcUywGkijVjZYMUrsm1j-9xgEObwgfEh_nvjlWhNzZCveCDfIBj98xqodQ2CZknz5-OOqhNQh0fTvSAK5KVPAoywXpDS4n5fhvVcWx8vUHe126vYrANLYvNI1FG5LWCPfXM1304048hqALKpffqSu9jyvoMjgCRVO1rexMsCC1",
"icon_drag_url": "",
"name": "Dual Berettas | Panther",
"market_hash_name": "Dual Berettas | Panther (Field-Tested)",
"market_name": "Dual Berettas | Panther (Field-Tested)",
"name_color": "D2D2D2",
"background_color": "",
"type": "Mil-Spec Grade Pistol",
"tradable": "1",
"marketable": "1",
"commodity": "0",
"fraudwarnings": "",
"descriptions": {
"0": {
"type": "html",
"value": "Exterior: Field-Tested",
"app_data": ""
},
"1": {
"type": "html",
"value": " ",
"app_data": ""
},
"2": {
"type": "html",
"value": "Firing two large-mag Berettas at once will lower accuracy and increase load times. On the bright side, you'll get to fire two large-mag Berettas at once. It has been painted in a black, grey and red color scheme.",
"app_data": ""
},
"3": {
"type": "html",
"value": " ",
"app_data": ""
},
"4": {
"type": "html",
"value": "The Arms Deal 3 Collection",
"color": "9da1a9",
"app_data": {
"def_index": "65535",
"is_itemset_name": "1"
}
},
"5": {
"type": "html",
"value": " ",
"app_data": ""
}
},
"owner_descriptions": "",
"actions": {
"0": {
"name": "Inspect in Game...",
"link": "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S%owner_steamid%A%assetid%D14429613083935122456"
}
},
"market_actions": {
"0": {
"name": "Inspect in Game...",
"link": "steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20M%listingid%A%assetid%D14429613083935122456"
}
},
"tags": {
"0": {
"internal_name": "CSGO_Type_Pistol",
"name": "Pistol",
"category": "Type",
"category_name": "Type"
},
"1": {
"internal_name": "weapon_elite",
"name": "Dual Berettas",
"category": "Weapon",
"category_name": "Weapon"
},
"2": {
"internal_name": "set_weapons_iii",
"name": "The Arms Deal 3 Collection",
"category": "ItemSet",
"category_name": "Collection"
},
"3": {
"internal_name": "normal",
"name": "Normal",
"category": "Quality",
"category_name": "Category"
},
"4": {
"internal_name": "Rarity_Rare_Weapon",
"name": "Mil-Spec Grade",
"category": "Rarity",
"color": "4b69ff",
"category_name": "Quality"
},
"5": {
"internal_name": "WearCategory2",
"name": "Field-Tested",
"category": "Exterior",
"category_name": "Exterior"
}
},
"classid": "350462890"
},
"success": true
}
}
So does anyone have any idea how I can return the market_hash_name? also please take note, I am fairly new to using Node.js.

data.result['350462890'].market_hash_name

Related

Why data is doubled, how I can fix it?

Good afternoon.
I have required json, which contains the basic template for the layout of Adaptive Cards (bot framework).
Here's this json:
{
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"version": "1.0",
"type": "AdaptiveCard",
"speak": "",
"body": [
{
"type": "TextBlock",
"horizontalAlignment": "center",
"text": "Все машины",
"weight": "bolder",
"isSubtle": false
},
{
"type": "TextBlock",
"text": "Внимание, вы вошли в режим тендера.",
"separator": true
}
],
"actions": [
{
"type": "Action.Submit",
"title": "Подтвердить лот(ы)",
"data": {
"msteams": {
"type": "messageBack",
"displayText": "Идет подтверждение ваших лотов, ожидайте!",
"text": "/accept",
"value": "{\"x\": \"bfVal\", \"y\": \"from value\"}"
}
}
},
{
"type": "Action.Submit",
"title": "Отменить все лоты",
"data": {
"x": "123",
"msteams": {
"type": "messageBack",
"displayText": "Идет отменение ваших лотов, ожидайте!",
"text": "/cancel",
"value": "{\"bfKey\": \"bfVal\", \"conflictKey\": \"from value\"}"
}
}
}
]
}
I also have a loop that takes data from my source and forms another json from it.
try {
// Pull in the data from Microsoft Graph.
const client = new SimpleGraphClient(tokenResponse.token);
const me = await client.getList();
var i = 0;
while (i < me['value'].length) {
feed = {
"type": "ColumnSet",
"separator": true,
"columns": [
{
"type": "Column",
"width": 1,
"items": [
{
"type": "TextBlock",
"text": "Продукт",
"isSubtle": true
},
{
"type": "TextBlock",
"size": "extraLarge",
"color": "accent",
"text": me.value[i].fields.Good,
"spacing": "none"
},
{
"type": "TextBlock",
"text": "Дата: " + dateFormat(me.value[i].fields.ShipmentDateTime, 'dd-mm-yyyy'),
"spacing": "yes"
}
]
},
{
"type": "Column",
"width": "auto",
"items": [
{
"type": "TextBlock",
"text": " "
},
{
"type": "Image",
"url": "https://png.pngtree.com/svg/20170614/engine_oil_410031.png",
"size": "medium",
"spacing": "yes"
},
{
"type": "TextBlock",
"text": " ID: " + me.value[i].fields.id,
"value": me.value[i].fields.id
}
]
},
{
"type": "Column",
"width": 1,
"items": [
{
"type": "TextBlock",
"horizontalAlignment": "right",
"text": "RUB",
"isSubtle": true
},
{
"type": "TextBlock",
"horizontalAlignment": "right",
"size": "extraLarge",
"color": "accent",
"text": me.value[i].fields.PricePerTon,
"spacing": "none"
},
{
"type": "Input.Toggle",
"title": "Приобрести лот",
"valueOn": "true",
"valueOff": "false",
"id": "buyGood",
"spacing": "yes"
}
]
}
]
}
tender.body.push(feed);
i++;
}
Then I combine these json.
This works well, but when you retrieve the data again, the data is doubled.
How can this be resolved?
Thanks in advance.
It looks like every time you create a new card, you are appending the JSON object you created in the while loop to your required JSON object. Consequently, the next time you try to create a new card, the data from the previous request is still stored in your required JSON object. To avoid this, create a copy of the required JSON Object and store it in a different variable before your while loop. You can use JSON.parse(JSON.stringify(obj)) to create a copy of a JSON Object.
Your code should look something like this:
// create a copy of the required JSON Object
// and store it in a new variable
const card = JSON.parse(JSON.stringify(tender));
var i = 0;
while (i < me['value'].length) {
let feed = {
"type": "ColumnSet",
"separator": true,
...
}
// push feed to `card` instead of `tender`
card.body.push(feed);
i++;
}
...
// send `card` to user instead of `tender`
await turnContext.sendActivity({
text: "Double Data Card",
attachments: [CardFactory.adaptiveCard(card)]
});

undefined error while while accessing JSON data

$http({
method: 'GET',
// url: "https://na30.salesforce.com/services/data/v36.0/query?q=SELECT+id,+name,+Product2.Name,+Product2.Description,+Product2Id,+Pricebook2Id,+Product2.Family,+Product2.Product_Image_URL__c,+Product2.Product_Image__c,+Pricebook2.name+from+PricebookEntry+where+(Pricebook2.Id+=+'01s360000049JQh'+and+Product2.Family+=+'CURRIES')",
url: $scope.finalurl,
headers: { 'Content-Type': 'application/json' ,
'Authorization' : $scope.result1 }
}).success(function(response) {
$scope.result= response.totalSize;
// $scope.size = response.
// alert(" Products records captured");
// alert($scope.result);
var y =response.records;
alert(y);
localStorage.setItem("offlinecurries1",JSON.stringify(y));
var x =localStorage.getItem("offlinecurries1");
alert(JSON.stringify(x[0].Name));
getting undefined error in the above alert
my response data is
{
"totalSize": 497,
"done": true,
"records": [{
"attributes": {
"type": "PricebookEntry",
"url": "/services/data/v36.0/sobjects/PricebookEntry/01u36000001de83AAA"
},
"Id": "01u36000001de83AAA",
"Name": "P-0025",
"Pricebook2Id": "01s36000004AGVLAA4",
"Product2": {
"attributes": {
"type": "Product2",
"url": "/services/data/v36.0/sobjects/Product2/01t36000001To1lAAC"
},
"Product_Image_URL__c": null,
"Description": "ACHAPPAM175GMS X12PKT",
"Family": null,
"Product_Image__c": "<img src=\" \" alt=\"Not Avaialble\" height=\"50\" width=\"50\" border=\"0\"/>"
},
"Product2Id": "01t36000001To1lAAC",
"Pricebook2": {
"attributes": {
"type": "Pricebook2",
"url": "/services/data/v36.0/sobjects/Pricebook2/01s36000004AGVLAA4"
},
"Name": "UK Pricebook"
}
}, {
"attributes": {
"type": "PricebookEntry",
"url": "/services/data/v36.0/sobjects/PricebookEntry/01u36000001de84AAA"
},
"Id": "01u36000001de84AAA",
"Name": "P-0026",
"Pricebook2Id": "01s36000004AGVLAA4",
"Product2": {
"attributes": {
"type": "Product2",
"url": "/services/data/v36.0/sobjects/Product2/01t36000001To1mAAC"
},
"Product_Image_URL__c": null,
"Description": "ADA RICE 200 x 30",
"Family": null,
"Product_Image__c": "<img src=\" \" alt=\"Not Avaialble\" height=\"50\" width=\"50\" border=\"0\"/>"
},
"Product2Id": "01t36000001To1mAAC",
"Pricebook2": {
"attributes": {
"type": "Pricebook2",
"url": "/services/data/v36.0/sobjects/Pricebook2/01s36000004AGVLAA4"
},
"Name": "UK Pricebook"
}
}]
}
var x =localStorage.getItem("offlinecurries1");
this line returns a string!
you need to parse the string into a json object, add this line right after
var x =localStorage.getItem("offlinecurries1");
x = JSON.parse(x)
Try this. You need to strigify when saving and while retrieving you need to parse the json using JSON.parse so it can be converted back to array.
var json = { "totalSize": 497, "done": true, "records": [{ "attributes": { "type": "PricebookEntry", "url": "/services/data/v36.0/sobjects/PricebookEntry/01u36000001de83AAA" }, "Id": "01u36000001de83AAA", "Name": "P-0025", "Pricebook2Id": "01s36000004AGVLAA4", "Product2": { "attributes": { "type": "Product2", "url": "/services/data/v36.0/sobjects/Product2/01t36000001To1lAAC" }, "Product_Image_URL__c": null, "Description": "ACHAPPAM175GMS X12PKT", "Family": null, "Product_Image__c": "" }, "Product2Id": "01t36000001To1lAAC", "Pricebook2": { "attributes": { "type": "Pricebook2", "url": "/services/data/v36.0/sobjects/Pricebook2/01s36000004AGVLAA4" }, "Name": "UK Pricebook" } }, { "attributes": { "type": "PricebookEntry", "url": "/services/data/v36.0/sobjects/PricebookEntry/01u36000001de84AAA" }, "Id": "01u36000001de84AAA", "Name": "P-0026", "Pricebook2Id": "01s36000004AGVLAA4", "Product2": { "attributes": { "type": "Product2", "url": "/services/data/v36.0/sobjects/Product2/01t36000001To1mAAC" }, "Product_Image_URL__c": null, "Description": "ADA RICE 200 x 30", "Family": null, "Product_Image__c": "" }, "Product2Id": "01t36000001To1mAAC", "Pricebook2": { "attributes": { "type": "Pricebook2", "url": "/services/data/v36.0/sobjects/Pricebook2/01s36000004AGVLAA4" }, "Name": "UK Pricebook" } }] };
var y = json.records;
alert(y);
localStorage.setItem("offlinecurries1", JSON.stringify(y));
var x = JSON.parse(localStorage.getItem("offlinecurries1"));
alert(x[0].Name);

Converting Multidimensional JSON key-value pairs into an Angular Menu (no Angular knowledge required)

I asked this question here:
Working With Dynamic Multidimensional key-value pairs in JSON
But it's become a bit more involved and I can't get where I'm going from that answer. If I have a data object that looks like this:
{
"email": "user#someco.com",
"firstname": "Bob",
"lastname": "Smith",
"company": "ACME",
"custom": {
"services": [
{
"name": "svc1",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc2",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc3",
"desc": "abcdefg",
"selected": "false",
"status": "None"
},
{
"name": "svc4",
"desc": "abcdefg",
"selected": "false",
"status": "None"
}
],
"fields": [
{
"name": "Products",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Product1",
"desc": "abcdef"
},
{
"name": "Product2",
"desc": "abcdef"
}
],
"services": [
"svc1",
"svc2",
"svc3"
]
},
{
"name": "Wines",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Wine 1",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
},
{
"name": "Fruits",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Fruit 1",
"desc": "abcdef"
},
{
"name": "Fruit 2",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
}
]
}
};
How can I convert that into an Angular menu? The menu would need to list all of the services, and then if the service has an associated item in "fields" that item should be listed underneath it. So for instance "svc1" and its description should be listed on a line (got that working) but then "Product1" and "Product2" with their descriptions should appear on the next two lines because you can see that "svc1" is listed in the "services" field for "Products." Similarly, "svc4" should appear on a line, and then "Wines" and its description on the next line because "svc4" appears in the "services" field of "Wines."
I think the best way is to unpack and re-pack this JSON object in sequential order in the Angular controller and then push this data out to the Angular view but there might be a solution using only the logic available from the view. I've tried a bunch of nested fors and ifs along these lines (very much not working):
var i, j;
var listArray = [];
for (i = 0; i < $scope.svcs.length; i++) {
var littleArray = [$scope.svcs[i].status, $scope.svcs[i].name, $scope.svcs.desc];
listArray.push[littleArray1];
for (j=0; j < $scope.jFA.length; j++) {
if ($scope.jFA[j] == $scope.svcs[i].name) {
if ($scope.jFA[j] == $scope.svcs[i].fields)
littleArray = [$scope.jFA[j].fields] //...etc
}
}
...but that logic just keeps getting more and more dense and isn't working no matter now I try to use it. I liked the simplicity in the answer to the other question but have not had success in replicating it.
So if someone can help me figure out how to get the data into the right sequence using JS I can handle the Angular part. Or if you're an Angular whiz and have an answer along those lines, even better.
So it was a little hard understanding your question, but I gave it my best shot. Does this fiddle show what you are trying to achieve? http://jsfiddle.net/arknr6qz/1/
JS:
var app = angular.module('TestApp',[]);
app.controller('TestController', function($scope)
{
$scope.checkService = function(service, fieldServices)
{
if (fieldServices.indexOf(service) != -1) return true;
return false;
};
$scope.data = {
"email": "user#someco.com",
"firstname": "Bob",
"lastname": "Smith",
"company": "ACME",
"custom": {
"services": [
{
"name": "svc1",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc2",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc3",
"desc": "abcdefg",
"selected": "false",
"status": "None"
},
{
"name": "svc4",
"desc": "abcdefg",
"selected": "false",
"status": "None"
}
],
"fields": [
{
"name": "Products",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Product1",
"desc": "abcdef"
},
{
"name": "Product2",
"desc": "abcdef"
}
],
"services": [
"svc1",
"svc2",
"svc3"
]
},
{
"name": "Wines",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Wine 1",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
},
{
"name": "Fruits",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Fruit 1",
"desc": "abcdef"
},
{
"name": "Fruit 2",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
}
]
}
};
});
HTML:
<div ng-app="TestApp">
<div ng-controller="TestController">
<div ng-repeat="service in data.custom.services">
{{ service.name }}
<div class="indent" ng-repeat="fields in data.custom.fields">
<span ng-if="checkService(service.name, fields.services)">
{{fields.services.values}}
<span ng-repeat="value in fields.values">
{{value.name}} - {{value.desc}}<br>
</span>
</span>
</div>
</div>
</div>
</div>
and finally css:
.indent {
margin-left:10px;
}

Passing function argument to retrieve data from an object

I am have some trouble with a script I am working on. I have been provided with an object with multiple items from a product catalog.
What I am trying to do is to write a function which to which will allow me to render this data easily.
<script type="application/javascript">
SKUinfo =
{
"s238554": {
"Age": {
"Description": "Age 18+",
"Thumbnail": "/productImages/assets/img/icon18.gif"
},
"Barcode": {
"Barcode": "50622132430794"
},
"Currency": "£",
"Description": "Description goes here",
"Id": 44305,
"Packshots": [
"/productImages/238556/1min.jpg",
"/productImages/238556/2med.jpg",
"/productImages/238556/3max.jpg"
],
"Pegis": [],
"Platform": {
"Button": "Xbox 360",
"ID": 0
},
"Publisher": {
"Description": null
},
"Release": "/Date(1392940800000+0000)/",
"Screenshots": [
{
"ScreenshotMax": "/productImages/238556/5scrmax1.jpg",
"ScreenshotMin": "/productImages/238556/4scrmin1.jpg"
}
],
"Title": "Product title 2 goes here",
"Variants": [
{
"Id": 58242,
"MaxOrderQuantity": 3,
"Presellable": true,
"Price": 29.97,
"PriceCultureFormat": "29.97",
"PriceWithCurrencyFormat": "£29.97",
"Sku": 238556,
"Type": {
"Description": "New"
}
},
],
"Vendor": {
"Description": ""
},
},
"s238556": {
"Age": {
"Description": "Age 18+",
"Thumbnail": "/productImages/assets/img/pegi/icon18.gif"
},
"Barcode": {
"Barcode": "5060134530794"
},
"Currency": "£",
"Description": "Description here",
"Id": 654654,
"Packshots": [
"/productImages/238556/1min.jpg",
"/productImages/238556/2med.jpg",
"/productImages/238556/3max.jpg"
],
"Pegis": [],
"Platform": {
"Button": "PlayStation 3",
"ID": 0
},
"Publisher": {
"Description": null
},
"Release": "/Date(1392940800000+0000)/",
"Screenshots": [
{
"ScreenshotMax": "/productImages/238556/5scrmax1.jpg",
"ScreenshotMin": "/productImages/238556/4scrmin1.jpg"
},
{
"ScreenshotMax": "/productImages/238556/7scrmax2.jpg",
"ScreenshotMin": "/productImages/238556/6scrmin2.jpg"
},
],
"Title": "Product title 2 goes here",
"Variants": [
{
"Id": 58242,
"MaxOrderQuantity": 3,
"Presellable": true,
"Price": 29.97,
"PriceCultureFormat": "29.97",
"PriceWithCurrencyFormat": "£29.97",
"Sku": 238556,
"Type": {
"Description": "New"
}
},
],
"Vendor": {
"Description": ""
},
"VideoHTML": "html here",
"status": {
"Response": "product found",
"Success": true
}
}
}
</script>
The above example is the output I get for two products.
If I try to get access to this data this is where I have a problem
<script type="application/javascript">
function getSKU(s)
{
console.log(SKUinfo.s.Title);
}
getSKU(s238554);
</script>
I imagine this is being caused when I am passing the argument s back to the function getSKU a the node selection in the data object. In this I would expect the console output to be the Title from SKU s238554.
What I get however, is: Uncaught ReferenceError: s238554 is not defined
I would appreciate any guidance that can be offered as I am a javascript novice.
Access your property by used[] on SKUinfo.s.Title like SKUinfo[s].Title
And also pass your property name within the quotes 's238554' as it's not variable.
Something like this.
function getSKU(s){
console.log(SKUinfo[s].Title);
}
getSKU('s238554'); // s238554 within quotes.

Facebook Open Graph not returning all results for Books.Read?

When using the Facebook Open Graph explorer, I run the following, to get a list of my books read.
/706685881/books.reads?limit=25&offset=0
This returns only 5 results, even though I have more books read than that, and I've explicitly requested up to 25 results. Following the paging link to the (theoretical) more results, shows a page with no more results.
here's my output of the query:
{
"data": [
{
"data": {
"book": {
"id": "452418224806835",
"url": "https://www.facebook.com/pages/Fantastic-Voyage/452418224806835",
"type": "books.book",
"title": "Fantastic Voyage"
}
},
"id": "10151871872740882"
},
{
"data": {
"book": {
"id": "106151566083577",
"url": "https://www.facebook.com/pages/The-Andromeda-Strain/106151566083577",
"type": "books.book",
"title": "The Andromeda Strain"
}
},
"id": "10151870390740882"
},
{
"data": {
"progress": [
{
"timestamp": 1388668020,
"percent_complete": 0
},
{
"timestamp": 1392949225,
"percent_complete": 100
}
],
"book": {
"id": "10150233066083545",
"url": "http://www.goodreads.com/book/show/10664113-a-dance-with-dragons",
"type": "good_reads:book",
"title": "A Dance with Dragons (A Song of Ice and Fire, #5)"
}
},
"id": "10151867499170882"
},
{
"data": {
"progress": [
{
"timestamp": 1391350736,
"percent_complete": 0
},
{
"timestamp": 1392569208,
"percent_complete": 100
}
],
"book": {
"id": "1390736374489290",
"url": "http://www.goodreads.com/book/show/18405477-city-of-the-sun",
"type": "good_reads:book",
"title": "City of the Sun"
}
},
"id": "10151860185710882"
},
{
"data": {
"book": {
"id": "526531387368738",
"url": "http://apps.facebook.com/bookscout/?currworkid=9000000000133742",
"type": "books.book",
"title": "Gates of Fire"
}
},
"id": "10151226827780882"
}
],
"paging": {
"next": "https://graph.facebook.com/706685881/books.reads?fields=data&limit=25&offset=25&__after_id=10151226827780882"
}
}
Anybody seeing what I am doing wrong?

Categories

Resources