How to parse below JSON - javascript

How to parse below JSON code in JavaScript where iterators are not identical?
var js= {
'7413_7765': {
availableColorIds: [ '100', '200' ],
listPrice: '$69.00',
marketingMessage: '',
prdId: '7413_7765',
prdName: 'DV by Dolce Vita Archer Sandal',
rating: 0,
salePrice: '$59.99',
styleId: '7765'
},
'0417_2898': {
availableColorIds: [ '249', '203' ],
listPrice: '$24.95',
marketingMessage: '',
prdId: '0417_2898',
prdName: 'AEO Embossed Flip-Flop',
rating: 4.5,
salePrice: '$19.99',
styleId: '2898'
},
prod6169041: {
availableColorIds: [ '001', '013', '800' ],
listPrice: '$89.95',
marketingMessage: '',
prdId: 'prod6169041',
prdName: 'Birkenstock Gizeh Sandal',
rating: 5,
salePrice: '$79.99',
styleId: '7730'
}
}
How can I parse this JSON in JavaScript? I want the values of prdName, listprice, salePrice in JavaScript?

var products = js; // more semantic
for (productId in products){
var product = products[productId];
console.log (product.prdName , product.listprice, product.salePrice);
}
js is an Object, the for (key in instance) iteration moves through the first level object's attributes, in this case 7413_7765, 0417_2898 and prod6169041, this keys are stored in the var productId, so products[productId] will return the value of this attributes.
Note that the "" in object keynames are not necesary.

You have already assigned the JSON to an object js.
You're trying to loop through JavaScript object, as Edorka mentioned iterate it.

Related

Google Tag Manager custom javascript variable to calculate the total cart value

I'm trying to calculate the value of the shopping cart based on data contained in my websites datalayer.
​{
event: 'checkout',
ecommerce: {
checkout: {
actionField: {step: 1},
products: [
{
name: 'Nude Fur Collar Quilted Puffer Jacket',
id: 'Nude-JKT-6824',
price: 39.99,
quantity: 1,
category: ['Clothing', 'Clothing/Jackets & Coats'],
variant: [false, false]
},
{
name: 'Black Side Stripe Knee Cut Jeans',
id: 'JN-004',
price: 19.99,
quantity: 1,
category: ['Clothing', 'Clothing/Jeans'],
variant: [false, false]
}
]
}
},
gtm.uniqueEventId: 12
}
I have created a custom javascript variable with the following script, that i got from a previous question on stack overflow here
Dinesh's script works, but the output returns this number
59.980000000000004
I would like it to return this
59.98
Here is Dinesh's code
function(){
var productList={{ecommerce}}.checkout.products;
var totalAmount=0;
for(var i=0;i<productList.length;i++)
{
totalAmount+=(productList[i].quantity)*(parseFloat(productList[i].price));
}
return totalAmount;
}
How can i modify this to output the result in the correct format, with two decimal places. Thanks.
try using toFixed() method when returning the totalAmount. This method is useful in keeping a specified number of decimal.so using toFixed(2) would return only 2 decimal places.
function(){
var productList={{ecommerce}}.checkout.products;
var totalAmount=0;
for(var i=0;i<productList.length;i++)
{
totalAmount+=(productList[i].quantity)*(parseFloat(productList[i].price));
}
return totalAmount.toFixed(2);
}

How to get certain number in this JavaScript array? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 5 years ago.
I'm new to JavaScript so my array mapping skills are bad, how would I find the assetid which is 47243781293 in this array? Thank you.
EconItem {
appid: 440,
contextid: '2',
assetid: '4723781293',
classid: '2674',
instanceid: '11040547',
amount: 1,
missing: false,
currency: false,
background_color: '3C352E',
icon_url: '...',
icon_url_large: '...',
tradable: false,
actions:
[ { link: 'http://wiki.teamfortress.com/scripts/itemredirect.php?id=5002&lang=en_US',
name: 'Item Wiki Page...' } ],
name: 'Refined Metal',
name_color: '7D6D00',
type: 'Level 3 Craft Item',
market_name: 'Refined Metal',
market_hash_name: 'Refined Metal',
commodity: false,
market_tradable_restriction: 7,
market_marketable_restriction: 0,
id: '4723781293',
fraudwarnings: [],
descriptions: [],
owner_descriptions: [],
owner_actions: [],
tags: [],
marketable: false
}
I think you mean to ask "..which is 47243781293 in this JSON" and not "...which is 47243781293 in this array". The object which you pasted above is a JSON representation. If that's what you are meaning to ask, please read below -
Given that the key id will always be present and the object value pasted above is assigned to variable EconItem, I would try something like this
If( EconItem['id'] === '47243781293' )
{
console.log('Asset id: 47243781293 present in the JSON object');
}
If you are not sure that key id will always be present in the object, I would first check for the key to be present using Object.keys(). Details can be found here - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
Hope that helps!
To get a value from the object, just refer to it's key: EconItem.assetid
For objects with multiple results, You can iterate on it, and output a particular value from your Object like so:
for (var i in EconItem)
{
console.log(EconItem[i].assetid);
//do more here
}
to find this in an array, you use filter which is a function that ships with every javascript array, using your object above for each EconItem
let array = [EconItem, EconItem]
search = array.filter(eachItem=>eachItem.assetId==='47243781293');
--> returns an array of items with assetId as 47243781293, now the first item should be your EconItem, i.e search[0];
Check example snippet
var items = [{
appid: 440,
contextid: '2',
assetid: '4723781293'
}, {
appid: 441,
contextid: '2',
assetid: '4723781292'
}];
// now we search with this 4723781293
var search = items.filter(function(item){
return item.assetid === '4723781293';
});
//show our search result
alert ("item appid is:"+search[0].appid+", context:"+search[0].contextid+", assetid:"+search[0].assetid);

How to parse a Non-Json data hemera

I am new to Json and JavaScript. Currently I have a url which returns a JSON response. But the problem is that, It is not in correct format. Please see my response below
var pd={ player:
{ id: 363609002,
game: 'bf4',
plat: 'pc',
name: 'm4jes',
tag: 'BPt',
dateCheck: 1487204427149,
dateUpdate: 1474581052618,
dateCreate: 1384980182606,
dateStreak: 1474581052618,
lastDay: '20160715',
country: '',
countryName: null,
rank:
{ nr: 121,
imgLarge: 'bf4/ranks/r121.png',
img: 'r121',
name: 'Major General II',
needed: 16110000,
next:
{ nr: 122,
imgLarge: 'bf4/ranks/r122.png',
img: 'r122',
name: 'Major General III',
needed: 16750000,
curr: 16720600,
relNeeded: 640000,
relCurr: 610600,
relProg: 95.40625 } },
score: 16724643,
timePlayed: 1476950,
uId: '2832665149467333131',
uName: 'm4jes',
uGava: '721951facb53ed5632e196932fb6c72e',
udCreate: 1319759388000,
privacy: 'friends',
blPlayer: 'http://battlelog.battlefield.com/bf4/soldier/m4jes/stats/363609002/pc/',
blUser: 'http://battlelog.battlefield.com/bf4/user/m4jes/',
editable: false,
viewable: true,
adminable: false,
linked: false },}
from the above response I have to get the output as :
{
game: 'bf4',
plat: 'pc',
name: 'm4jes',
tag: 'BPt',
score: 16724643,
timePlayed: 1476950
}
By which method I can get the required out in Javascript
First of all the URL is not returning a JSON response but a JS object literal. The difference is explained here.
You have to get the string from the url. You can use the jQuery method get():
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var jqxhr = $.get( "https://api.bf4stats.com/api/playerInfo?plat=pc&name=m4jes&output=js", function() {
//Insert the rest of the code here
});
</script>
Then, jqxhr.responseText is the string which correspond to the object we want. With eval, we transform the string into an object:
pd = eval(jqxhr.responseText);
So here we have an object literal with all the pairs name/value. You can access the values you want by using the dot notation. If you want to get the name of the game for example, you can write this:
pd.player.game
So this leads to :
var myNewObject = {
game: pd.player.game,
plat: pd.player.plat,
name: pd.player.name,
tag: pd.player.tag,
score: pd.player.score,
timePlayed: pd.player.timePlayed,
}
Then, you have to transform this JS object literal into a JSON by using the JSON.stringify() method:
console.log(JSON.stringify(myNewObject, null, '\t'));
It returns what you want:
{
"game": "bf4",
"plat": "pc",
"name": "m4jes",
"tag": "BPt",
"score": 16724643,
"timePlayed": 1476950
}
So here is the full code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var jqxhr = $.get( "https://api.bf4stats.com/api/playerInfo?plat=pc&name=m4jes&output=js", function() {
pd = eval(jqxhr.responseText);
var myNewObject = {
game: pd.player.game,
plat: pd.player.plat,
name: pd.player.name,
tag: pd.player.tag,
score: pd.player.score,
timePlayed: pd.player.timePlayed,
}
console.log(JSON.stringify(myNewObject, null, '\t'));
});
</script>

javascript push() method for adding object to array of objects

var model = {
cats: [
{
clickCount: 0,
name: "Panther",
imgUrl: "images/cat1.png"
},
{
clickCount: 0,
name: "Tiger",
imgUrl: "images/cat2.png"
},
{
clickCount: 0,
name: "Rocky",
imgUrl: "images/cat3.png"
},
{
clickCount: 0,
name: "Marshal",
imgUrl: "images/cat4.png"
},
{
clickCount: 0,
name: "Simpson",
imgUrl: "images/cat5.png"
},
{
clickCount: 0,
name: "Kajol",
imgUrl: "images/cat6.png"
}
]
};
catObject = {
name: document.getElementById('text-name').value,
url: document.getElementById('text-url').value,
count: document.getElementById('text-count').value
};
model is an array of objects. I am trying to add another object using model.cats.push(catObject);
where text-name, text-url, text-count are ids of textboxes in a form.
I am not getting desired results. I am seeing that only catObject.name is getting pushed onto model.cats and catObject.url and catObject.count is not getting added and hence 'undefined' are values of the model.cats.imgUrl and model.cats.clickCount.
I can add full code if required. I tried so may things.. Could someone check if I am missing anything here? Thanks in advance.
Correction
model is not an array of objects rather model is an object that contains a property (i.e. cats) which is an array of objects.
You're correct
From your description, it is clear that you have successfully pushed catObject into cats using model.cats.push(catObject);
What went wrong
You might have used loop to access the elements inside cats array and got undefined for model.cats.clickCount and model.cats.imgUrl of only the last object you've pushed because you named properties of catObject as url and count (i.e. instead of imgUrl and clickCount). So, just change the property names to imgUrl and clickCount to fix the issue.
Corrected code here

JSON to AS3 Object issue

I am new to JSON to AS3 Objects and am having issues trying to create an AS3 object that I can reference. Here is the JSON:
{
demo: {
Male: {
21-30: 2,
31-40: 0,
41-50: 0,
51-60: 0,
61-70: 0,
71-80: 0,
81+: 0
},
Female: {
21-30: 7,
31-40: 0,
41-50: 0,
51-60: 0,
61-70: 0,
71-80: 0,
81+: 0
}
},
days: 0
}
Here is the parsing code:
var JSONRequest: URLRequest = new URLRequest();
JSONRequest.method = URLRequestMethod.POST;
JSONRequest.url = "https://www.urlhere.com;
var loader: URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, handleResponse);
loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
loader.load(JSONRequest);
function handleResponse(event:Event):void{
var returnData:String = loader.data;
var parsedData:Object = JSON.parse(returnData);
}
I have tried and successfully looped through the object with for loops, but I don't want to have to do that, I want to be able to access the data as an object or array by accessing the properties in dot syntax. Object[0].property etc...
The really tricky part is that I don't know how large or how deep the data is nested. The one I added here is simple.
Here is more like what I will be getting:
{
products: {
Home & Garden: {
Kitchen: {
202: {
brand: "OXO",
description: "12 piece locktop container set",
descriptionLong: "Prepping, cooking and cleaning",
listPrice: "36.32",
sku: "925776",
upc: "719812032528"
},
238: {
brand: "Excalibur",
description: "Excalibur 2400 4-Tray Dehydrator",
descriptionLong: "Dehydration is the healthiest",
listPrice: "168.54",
sku: "947741",
upc: "029743240009"
},
352: {
brand: "Nostalgia",
description: "OldFashioned Kettle Corn Maker",
descriptionLong: "With the Nostalgia Electrics ",
listPrice: "35.49",
sku: "925843",
upc: "082677300218"
},
370: {
brand: "Joseph Joseph",
description: "Nest Plus Measuring (Set of 5 Cups - Multi Coloured)",
descriptionLong: "Nest™ Cups are a range of 5",
listPrice: "2.46",
sku: "926733",
upc: "5028420400342"
},
605: {
brand: "Nostalgia",
description: "Margarator-Frozen Drink Maker",
descriptionLong: "Mix up great-tasting margaritas",
listPrice: "140.68",
sku: "925851",
upc: "082677135889"
}
},
Housewares: {
206: {
brand: "Dyson",
description: "Dyson DC44 Animal",
descriptionLong: "DC44 Animal has a detachable",
listPrice: "406.51",
sku: "922846",
upc: "879957006362"
}
}
}
I will also add that I can request the formatting of the JSON I am receiving, so if there is a better way to format the data coming from the server, I am open to that.
Any help would be great.
I want to be able to access the data as an object or array by accessing the properties in dot syntax.
Use JSON.stringify and a replace callback before the parse call to rename the keys so you can access them via dot notation:
function newkey()
{
return "key" + Number(Math.random() * 1000).toFixed() + RegExp.$1
}
//Stringify JSON
var foo = JSON.stringify(parsedData);
/*
Replace numeric keys with a random number without replacing the delimiter
Replace spaces with underscores
*/
var bar = foo.replace(/\d+("?:)/g, newkey).replace(/\s/g,"_")
//Parse resulting string
var baz = JSON.parse(bar);
References
JSON - AS3 API Reference

Categories