creating an object from JSON - javascript

I've seen a lot of different answers to this question and have tried applying their code to my project but none of these solutions seem to work for the data I have.
I need to turn this output into several objects:
[{"creature":{"id":1,"name":"R.I.P.","sprite_location":null,"health_points":0,"attack":0,"defense":0,"action_points":0,"attack_cost":0}},{"creature":{"id":2,"name":"R.I.P.","sprite_location":"http://chunkofwhat.com/games/Parousia/sprites/rip.gif","health_points":0,"attack":0,"defense":0,"action_points":0,"attack_cost":0}},{"creature":{"id":3,"name":"Bull.","sprite_location":"http://chunkofwhat.com/games/Parousia/sprites/bull.gif","health_points":50,"attack":8,"defense":20,"action_points":9,"attack_cost":5}},{"creature":{"id":4,"name":"Swallow.","sprite_location":"http://chunkofwhat.com/games/Parousia/sprites/swallow.gif","health_points":30,"attack":12,"defense":10,"action_points":13,"attack_cost":5}},{"creature":{"id":5,"name":"Kappa.","sprite_location":"http://chunkofwhat.com/games/Parousia/sprites/kappa.gif","health_points":40,"attack":6,"defense":15,"action_points":9,"attack_cost":3}},{"creature":{"id":6,"name":null,"sprite_location":null,"health_points":null,"attack":null,"defense":null,"action_points":null,"attack_cost":null}}]
When I try jQuery.parseJSON(), it just gives me a bunch of [object Object]s but I can't refer to creature[1].id etc.
Again, I know this is a frequently asked question. I really have been through many other examples but they just didn't work out for me.
Thank you.

Each object has one property (creature) with another object as it's value.
result_of_parsing_json[1].creature.id

var creatures = JSON.parse('big_json_string');
for (var i = 0; i < creatures.length; i++) {
var creature = creatures[i].creature; // this is how your object is formatted
console.log(creature.name);
}
/*
R.I.P.
R.I.P.
Bull.
Swallow.
Kappa.
null
*/
Each creature is nested within another object, and since it's an array of objects (that contain the creature), you have to iterate over it with a for loop, to make use of it.
Your parsing of the JSON, then, was most likely correct, but the logic that came afterwards was not (at a total guess).

Your code seems perfectly valid. Try this jsfiddle.
var creatures = $.parseJSON(yourJSONString);
alert(creatures[0].creature.name);​ // alerts "R.I.P"
Do you need any specific clarifications?

Related

How to use JavaScript to get all element from a dynamic scroll list?

Like the title said, how do I get all elements from a scroll div? The elements in the scroll list are loaded and destroyed dynamically.
I tried to crawl all course names from this website:
https://public.enroll.wisc.edu/search?term=1204
The code below only works for one time:
let list = document.getElementsByClassName('md-virtual-repeat-scroller')[0]
let childs = document.getElementsByClassName("result__name")
console.log(childs[0].innerText)
However, if I do this, I will get the same result for 10 times:
let list = document.getElementsByClassName('md-virtual-repeat-scroller')[0]
for(let i = 0; i < 10; i++) {
let childs = document.getElementsByClassName("result__name")
for(let j = 0; j < childs.length; j++) {
console.log(childs[j].innerText)
}
// scroll by 1000px every time
list.scrollBy(0, 1000)
}
I don't know what's the problem. Is it because that scrollBy() works asynchronously? But I tried to use async and await. It still doesn't work.
Give more information in less words as a possible. Many problems could be related to browser and its version, for example. How is this script called? Are you giving commands via browser console? Have you done a copy of the site and performed some modification on it? It's hard to understand the problem in a realistic level.
Tip: Avoiding use innerText. It's slower and is supported in many browsers only for compability to scripts written to old versions of IE. (I don't know why so many examples in internet use it as first option). User textContent instead.
It's always good to test the returned value of a function/methods - specially during the development of the program.
Never ask to the StackOverFlow community (and to any other) to write progams for you!
You question "how do I get all elements from a scroll div?" is so "loose". scroll div? The answer to this, independently to the "type of div" (and tag!) would be found below.
Your code seems to be no sense in order to do what you want. Why iterate from 0 to 10?
Look at this snipet. I think it will help you
const list = document.getElementsByClassName('md-virtual-repeat-scroller')[0];// if there is no intention to reassign it. Use [0] if you are sure it's the first element of this collection
let childs = list.getElementsByClassName("result__name"); // get only elements inside the first variable!
Use the iterator of the variable.
for(item of childs)
{
/*code*/
}
I am sure you will achieve your goals!
And never suggest us (Community) to code for you or even to resolve your problem. This sound very agressive! To you too! I'm sure.
I solved my problem by reading this article:https://intoli.com/blog/scrape-infinite-scroll/
The reason why I kept getting the same elements is that scrollBy() works asynchronously, so I have to wait then evaluate the page again. I am using puppeteer by the way.
please read the article, super helpful.

Extendscript load content from var

In Javascript or PHP this is fairly easy but doesn't seem to work for extendscript.
I have a search function that stores it's results in a var. I want to see what is in the var after the function runs. So usually I use a alert() but InDesign comes up with a box containing [object Word].
Here is what I do:
var myFound = myDoc.findGrep();
alert(myFound);
InDesign throws me this box:
If I do the following:
alert(myFound.length);
Any ideas how to "reveal" my content?
If someone wants to know how to fix it:
Create an array around the for loop and gather the information in it.
After that alert the array like this:
var myFound = myDoc.findGrep();
var result = new Array();
for(i=0; i<myFound.length; i++)
{
result[result.length] = myFound[i].contents;
}
alert(result);
The result of a grep search is an array. You need loop through it and access the word.contents
In this case, I entirely use $.writeln() instead of alert().
or use
milligramme/scriptui_scrollable_alert
I have found this site (http://jongware.mit.edu/idcs6js) immensely useful in understanding ExtendScripts InDesign objects. In particular, your Words object is here, which is an array of Word instances.
In addition, I've used Use Visual Studio Code with the ExtendScript Debugger which helpful for watching variables.

Getting length (size? count?) of an array in Parse.com cloud code

I believe in javascript, arrays have a ".count" property. However, I believe that when writing Parse cloud code, effectively you cannot use this since .count is in a word, used by Parse (for queries).
(1) Is that correct, and is the reason I gave correctly stated or a shambles?
I believe (it seems to work) you can go ahead and use .length in Parse cloud code for the length of an array; but I'm confused "why" since javascript doco says .length
(2) Is that correct - if so why can it be done?
You inevitably use "underscore" library in Parse projects; in fact does that library offer a way to get the size/length/count of an array?
(3) Is there yet another way, using _ ?
I swear I have seen Parse cloud code using "size" (something or other like that) in relation to arrays;
(4) Is there an idiom using something like 'size' ?
Finally, indeed, considering this typical example of using _,
Parse.Cloud.afterSave("Employee", function(request)
{
var company = request.object.get("company");
var query = new Parse.Query("Employee");
query.equalTo("company", company);
query.include("company");
var justEmails = new Array();
query.each(function(employee)
{
var thatEmail = employee.get("email");
justEmails.push(thatEmail);
}
).then(function()
{
var kount = justEmails.length;
console.log(">>> count is " + kount );
justEmails = _.uniq(justEmails);
kount = justEmails.length;
console.log(">>> but count is now " + kount );
});
});
(5) is there a way to do that in "one line", saying something like _.uniq(justEmails).sizeOrWhateverTheHell();
Finally in summary,
(6) what then is the best and most sensible and most idimoatic way to get simply the length of an array, in javascript in the Parse cloud code milieu -- is it indeed .length?
There is no such thing as count. Arrays (and strings) have a .length property. Use it.
I have no idea what this is asking.
No, use .length.
See 3
_.uniq(whatever).length
See 1
It's just JavaScript.
You are correct and the best way to get the number of elements of an array in javascript (and in Parse cloud code) is to use array.length
Length is the property of the array, whereas size is a function that's defined in some javascript frameworks. Always use the length property to get the number of elements in an array.

How do I extract a JavaScript function from the following page?

I'm trying to follow this tutorial
http://eloquentjavascript.net/chapter8.html
It mentions a function inPlacePrinter. I cannot find the source code for this in the actual text. I have tried poking around in view source since the interactive version seems to work but cannot locate the raw code. How do I find it?
It is defined in http://eloquentjavascript.net/js/chapter/oo.js.
In oo.js there is this line:
var div = __ENV.parent.DIV();
__ENV is not defined elsewhere, nor in any of the other js files, maybe is part of the MochiKit framework used on page.
You can replace inPlacePrinter() with this 2 functions in order to show the output in browser console:
function show(x){
var show = "";
for (var y = 0; y < arguments.length; y++) {
show += arguments[y];
}
console.log(show);
}
function showTerrarium(terrarium){
this.show(terrarium);
return function() {
console.clear();
this.showTerrarium(terrarium);
}
}
And used them in this way
/*replace:*/ terrarium.onStep = partial(inPlacePrinter(), terrarium);
/*with:*/ terrarium.onStep = partial(showTerrarium(terrarium), terrarium);
Maybe there is a better solution, but this worked.
thats a big tutorial. About half way down the page is this statement:
But all these extra variables can get messy. Another good solution is to use a function similar to partial from chapter 6. Instead of adding arguments to a function, this one adds a this object, using the first argument to the function's apply method:
Is the function inPlacePrinter in the object called partial in chapter 6?
Try using something like Firebug to look at the JavaScript files.

'Best' way to pull data relative to a div?

This answer suggested i should put my data in JS instead of a textarea.
Thinking about it i could have scripts and do something like myarray[i]="data" where i is the index of my for loop. However when i click a div how do i find out what i is? I have used var data = $(this).parent('.parent').find('.valuestr').eq(0).val(); which is extremely simple. Should i use a script or should i continue to do it with a textarea? if i should use a script 1) Whats the easiest way to find i and 2) Is it bad pratice to have dozens or hundreds of <script> in my html? or i can go through the loop twice but i still dont know the easiest way to find i. I would have to store it somewhere or go through multiple tags and count them.
Answering the other part of your question:
2) Is it bad pratice to have dozens or
hundreds of in my html?
It will depend on who you talk to, but in general, yes, I think it is. There's actually a push for html to be completely devoid of Javascript, save loading of .js files. For more info, look into unobtrusive javascript.
http://en.wikipedia.org/wiki/Unobtrusive_JavaScript
jQuery has a data() function just for that.
You store arbitrary data related to some element like this:
$('#my_div').data('foo', 'bar');
$('#my_div').data('hello', 'world');
Then you retrieve it like this:
alert($('#my_div').data('foo')); // alerts "bar".
alert($('#my_div').data('hello')); // alerts "world".
Since each DOM_Element is just an object, you can declare a variable in the object.
for(var i = 0; i < elements.length; i++)
{
elements[i].i = i;
elements[i].onclick = function(){
alert(this.i);
}
}

Categories