JSON to AS3 Object issue - javascript

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

Related

Split object into multiple ordered arrays based on identity of 1 spesific value

Not quite sure if that title was the best I could do.
I'm a pretty new to js and keep running into problems ... I hope some of you have the time to give me a pointer or two on this scenario.
I have several objects that looks pretty much like this - except from the fact that there are 28 instances of every "room" type. I need to split this object into multiple objects - one for each "room" type. In some of my objects there are only one room type - whilst in others there are 3 or 4.
[ { id: 1
created: 2018-12-29T13:18:05.788Z,
room: 'Double Room'
type: 'Standard'
price: 500
},
{ id: 29
created: 2018-12-29T13:18:05.788Z,
room: 'Twin Room'
type: 'Standard'
price: 500
},
{ id: 58
created: 2018-12-29T13:18:05.788Z,
room: 'Family Room'
type: 'Standard'
price: 900
},
]
Oh, and it's important that the instances don't "loose" their order in the array - since it's date related and need to be presentet in an ascending order. And vanilla js only.
Is array.map() the function I'm looking for to solve this problem? Is it posible to do this without iteration?
My final goal is to create some kind of generic function that can sort this out for all my objects.
And guys: happy hollidays!
You could take an object as hash table for the wanted groups. Then iterate the objects and assign the object to the group. If the group does not exist, create a new group with an array.
function groupBy(array, key) {
var groups = Object.create(null);
array.forEach(o => (groups[o[key]] = groups[o[key]] || []).push(o));
return groups;
}
var data = [{ id: 1, created: '2018-12-29T13:18:05.788Z', room: 'Double Room', type: 'Standard', price: 500 }, { id: 29, created: '2018-12-29T13:18:05.788Z', room: 'Twin Room', type: 'Standard', price: 500 }, { id: 58, created: '2018-12-29T13:18:05.788Z', room: 'Family Room', type: 'Standard', price: 900 }],
groupedByRoom = groupBy(data, 'room');
console.log(groupedByRoom);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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 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>

How to create an instance with the new constructor for every node in a json?

I am about to start writing an App which is an Organizational Chart and I will be using this library where the code example they provide is very clear:
var options = new primitives.orgdiagram.Config();
var items = [
new primitives.orgdiagram.ItemConfig({
id: 0,
parent: null,
title: "Scott Aasrud",
description: "VP, Public Sector",
image: "demo/images/photos/a.png"
}),
new primitives.orgdiagram.ItemConfig({
id: 1,
parent: 0,
title: "Ted Lucas",
description: "VP, Human Resources",
image: "demo/images/photos/b.png"
}),
new primitives.orgdiagram.ItemConfig({
id: 2,
parent: 0,
title: "Joao Stuger",
description: "Business Solutions, US",
image: "demo/images/photos/c.png"
})
];
options.items = items;
options.cursorItem = 0;
options.hasSelectorCheckbox = primitives.common.Enabled.True;
jQuery("#basicdiagram").orgDiagram(options);
which is weird for me, is the items array, I will not be placing that array in the main file where I am going to be constructing my App. Actually the data will come from a json, so just imagine that items array coming from a separate json file, so . . . what should I do in order to put that data in a json, and then call it in my main file, and create the instances like this new primitives.orgdiagram.ItemConfig({ . . . }) for every node in that json?
What are your suggestions?
You can use [].map. It creates a new array with the values returned by a function called with each array item as an argument:
var items = JSON.parse(myjson).map(function(item) {
return new primitives.orgdiagram.ItemConfig(item);
});
Actually, that definition of nodes via new object is done for the sake of code readability, in order to reference user to options of proper object type. Chart supports JSON objects as well.
var options = new primitives.orgdiagram.Config();
var items = [
{
id: 0,
parent: null,
title: "Scott Aasrud",
description: "VP, Public Sector",
image: "demo/images/photos/a.png"
},
{
id: 1,
parent: 0,
title: "Ted Lucas",
description: "VP, Human Resources",
image: "demo/images/photos/b.png"
},
{
id: 2,
parent: 0,
title: "Joao Stuger",
description: "Business Solutions, US",
image: "demo/images/photos/c.png"
}
];
options.items = items;
options.cursorItem = 0;
options.hasSelectorCheckbox = primitives.common.Enabled.True;
jQuery("#basicdiagram").orgDiagram(options);

How to parse below JSON

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.

Categories