How can I print javascript objects? - javascript

I have an object
var object= {}
I put some data in the object and then I want to print it like this
document.write(object.term);
the term is a variable that changes depending on different situations. When I try printing this it comes up with undefined.
How would it be done?
Update:
this is the code I am dealing with. I guess it probably isn't the same as what I said above because I am doing it in selenium with browsermob, I just thought it would be similar to document.write(). Here is the code
var numCardsStr = selenium.getText("//div[#id='set-middle']/div[2]/h2");
var numCards = numCardsStr.substr(4,2);
browserMob.log(numCards);
var flash = {}
for(i=0; i<(numCards); i++){
var terms = selenium.getText("//div[#id='words-normal']/table/tbody/tr[" + (i + 2) + "]/td[1]");
var defs = selenium.getText("//div[#id='words-normal']/table/tbody/tr[" + (i + 2) + "]/td[2]");
flash[terms] = defs;
browserMob.log(flash.terms);
}

EDIT: You're using two different variable names, flash and flashcards. I don't know if they are meant to be the same thing, but you are setting the value using the [] notation, then getting it using . notation.
Try:
var flash = {};
...
flash[terms] = defs;
browserMob.log(flash[terms]);
If term is a variable to represent the property you are retrieving, then you should use the square bracket notation for getting the property from the object.
Example: http://jsfiddle.net/xbMjc/ (uses alerts instead of document.write)
var object= {};
object.someProperty = 'some value';
var term = "someProperty";
document.write( object[term] ); // will output 'some value'

If you're using document.write(), there's a good chance you are trying to reference the object before it's been instantiated. My advice: don't use document.write() unless you need it in a template. For all other purposes, wait till the page loads and then run your script as an event handler.
There could be other reasons for the failure, but your code sample isn't complete enough for a diagnosis.

To output the whole object as text, use a JSON library:
<script type="text/javascript" src="http://www.JSON.org/json2.js"></script>
.
var o = { "term": "value" };
document.write(JSON.stringify(o, null, 4));
This will output the object as a string and indent 4 spaces to make it easy to read.
What you do is this:
var terms = "abcd";
var defs = "1234";
var flash = {};
flash[terms] = defs;
This creates this object:
{
"abcd": "1234"
}
If you want to go through the properties (i.e. "abce"), do this:
for (var key in flash) {
document.write('Key "' + key + '" has value "' + flash[key] + '"<br/>');
}
This will output:
Key "abcd" has value "1234"

Because I haven't seen this mentioned yet:
var a = {prop1:Math.random(), prop2:'lol'};
a.toString = function() {
output = [];
for(var name in this) if(this.hasOwnProperty(name) && name != 'toString') {
output.push([name, this[name]].join(':'));
}
return "{\n"+output.join(",\n\t")+"\n}";
};
document.write(a);
// should look like:
/*
{
prop1:0.12134432,
prop2:lol
}
*/
In the case that you're defining an object class, like MyObj:
var MyObj = function(id) {
this.someIdentity = id;
};
MyObj.prototype.toString = function() {
return '<MyObject:'+this.someIdentity+'>';
};
And then anytime you write something like
document.write(new MyObject(2));
It'll appear as <MyObject: 2>.

Avoid document.write
If you use Firefox, install firebug and use it's console api
The same console apis should work in chrome too.
For IE, get companion js
In javascript, obj.propertyname is used if the property name is known before hand. If it's not, then:
if pn contains the property name, obj[pn] should give you the value.

Well in firefox and in Chrome/Safari you could simply use...
var myObj = {id: 1, name: 'Some Name'};
window.console.log(myObj);
And the console will output something like "Object"
If you are in Chrome you could inspect the internal values of the object with ease using the built in developer console.
If you use firefox the output should come out of firebug as well...
I'm stating this as an alternative of using document.write as it seems a little bit invasive to me to output content on the document...

Related

method plugin doesn't work within Function Constructor

What I'm trying to achieve in JavaScript is to make a method of the plugin I'm working with (called "Plugin") flexible. The plugin runs in an iFrame and has cross-domain trust settings applied. I want to use variables to build the method parameter rather than hard code it.
The hardcoded version is shown below and I've double checked this works. I've used it in functions and in a Function constructor. Both work.
window.Plugin.Session.Tags({
TagName: 'SomeTagName',
TagValueTagging: 'sometagvalue; secondtagvalue',
TagValueTaggingReset: '*'
}).Update();
My objective is to replace the 'sometagvalue' with a variable, so I can set the tag dynamically. The help says the parameter is a constant JSON string.
I've tried the following things:
build the parameter as string. Result: Though myText holds the exact same string as in the hardcoded version, the method is not executed.
var myTag = '\\'DEELNEMER ; name\\' ';
var myText = "{TagName : 'Workflow'," +
" TagValueTagging : " + myTag +
", TagValueTaggingReset : '*'}";
alert("myText = " + myText);
x = window.Plugin.Session.Tags(myText);
x.Update();
2) using new Function constructor. I created a variable with the session object and inserted that as parameter. In order to proof myself that I working with the right object, I've put it's LID in an alert as well outside as inside the constructor. Result: the Session.LID was the same inside and outside the constructor, but tagging did not happen.
var myFunction = "alert(\"in constructor Session.LID = \" + prmSession.LID); window.addTag =
prmSession.Tags({TagName : \'Workflow\', TagValueTagging : \'DEELNEMER\' , TagValueTaggingReset :
\'*\'}); window.addTag.Update();"
var addTagFunction = new Function("prmSession", myFunction)
var prmSession = window.Plugin.Session;
alert("in main function Session.LID = " + prmSession.LID);
addTagFunction(prmSession);
3) using JSON stringify. Again Result: Tag was not set, in neither variant..
var myTag = 'DEELNEMER ; name ';
var obj = new Object();
obj.TagName = "Workflow";
obj.TagValueTagging = myTag;
obj.TagValueTaggingReset = "*";<br/>
var myJSON= JSON.stringify(obj);
Plugin.Session.Tags(myJSON).Update();<br/>
/*variant 2*/<br/>
var myObjParsed = JSON.parse(myJSON);
Plugin.Session.Tags(myObjParsed).Update();
I would be very greatful for a tip how to solve this issue.
Regards
Plugin appears to translate the javascript into backend data queries during the compilation of the solution.
The use of parameters is therefore not possible.

JSON.parse error....unexpected token{ from 2nd

My JSON.parse is successful when it is called first. But from 2nd call, unexpected token error occurs.
I found from the search in stackoverflow some explanation for other's question below..
"If you parse it again it will perform a toString-cast first so you're parsing something like "[object Object"] which explains the unexpected token o "
How can i make the fresh parse. my code is like below.
var musicEntry="";
function parsing(){
...
for(var i=0;i<musicList.length;i++){
musicEntry=musicEntry+ '{"fileName":"'+musicList[i].title+'"},';
}
.....
var musicJsonObjString='{"music":['+ musicEntry +']}';
musicJsonObj=JSON.parse(musicJsonObjString);
}
I'd recommend using JSON.stringify() instead of trying to write your own JSON encoder. Whilst your approach might now work with the trailing comma issue fixed, you'll also need to guard against reserved characters in your music title attribute.
Simply build a JavaScript object (or array) and give it to JSON.stringify(obj)
Working example
var musicList = [{
title: 'foo'
}, {
title: 'bar'
}];
var array = [];
for (var i = 0; i < musicList.length; i++) {
array.push({fileName: musicList[i].title})
}
var musicJsonObjString = JSON.stringify({music: array});
var musicJsonObj = JSON.parse(musicJsonObjString);
console.log("music", musicJsonObj);
You need to remove last comma from your array:
var musicJsonObjString='{"music":[' + musicEntry.substr(0, musicEntry.length - 1 ) + ']}';

Json string values in javascript

I have following JSON string in a global variable in Javascript
var domains = {
"DomID00001": {
"ID":"DomID00001",
"Name":"Testdomein1"
},
"DomID00002": {
"ID":"DomID00002",
"Name":"Testdomein2"
}
};
What is the best way to retrieve the values from this JSON string and be able to use them in Javascript individually?
If I just alert the domains var it says = [object Object]
Using alert() will not show you objects, this is one of the big advantages of the console. Check this fiddle and use the console (pressing F12 on your browser). Then you understand how to refer to what is inside that object.
var domains = {"DomID00001":{"ID":"DomID00001","Name":"Testdomein1"},"DomID00002":{"ID":"DomID00002","Name":"Testdomein2"}};
console.log(domains);
console.log(domains.DomID00001);
console.log(domains.DomID00001.ID);
Since the keys are variable, you should probably use a for..in loop:
for( domid in domains) if( domains.hasOwnProperty(domid)) {
console.log(domid,domains[domid].ID,domains[domid].Name);
}
Try this:
var domains = {"DomID00001":{"ID":"DomID00001","Name":"Testdomein1"},"DomID00002":{"ID":"DomID00002","Name":"Testdomein2"}};
var strName1 = domains.DomID00001.Name;
var ID1 = domains.DomID00001.ID;
alert('Name: ' + strName1 + ' - ID: ' + ID1);

Javascript Form: Only Changed Fields

I have a php-site with a form on which i output preselected values via php. On form submit I want to check which values have changed and just submit these via javascript.
These are the preselected values I passed over from php. It's important that I keep the associative array structure.
var pbData = jQuery.parseJSON("{
"GameMode":"DEATHMATCH",
"Current Map":"VEGAS JUNKYARD",
"Current Missions":["VEGAS JUNKYARD","VILLA","PRESIDIO","KILL HOUSE","MURDERTOWN","CQB TRAINING","STREETS","THREE KINGDOMS CASINO","IMPORT\/EXPORT;"],
"RoundDuration":"3 minutes"}");
I marked the error in the code.
<script>
function displayVars(){
var form = document.getElementById('settings');
var elems = form.elements;
var txt = "";
for (var index = 0; index < elems.length; index++){
var selIndex = elems[index].selectedIndex;
if (typeof selIndex !== "undefined"){
//the Index Name in the json-object and the name of the form-field are the same
var idxName = elems[index].name;
//HERE is the problem. I want to access the subobject via a variablename, so i can iterate through it, but that doesnt work.
console.log ("pbData default = "+pbData.idxName); //always undefined
if (elems[index].value !== pbData.idx_name){
//building a POST-Url
txt = txt + elems[index].name + "=" + elems[index].options[selIndex].value+"&";
}
}
}
console.log (txt);
return false;
}
</script>
I know that I could do this differently, also with jQuery. In my case as I have the preselected values as a php-variable in any case, i think it's easier like this.
I would really like to know how I can iterate through the subobjects via a variable that contains the object names.
This is due to how you'e trying to access the property of the (JSON) object. Consider
var o1 = {idxName: true},
o2 = {foo : 'bar'},
idxName = 'foo';
o1.idxName; // true
o2.idxName; // undefined
o2[idxName]; // 'bar'
You need to access the property via pbData[idxName].
Additionally, you're not escaping quotes in your JSON string, and line breaks need to be escaped as follows
var pbData = jQuery.parseJSON("{\
\"GameMode\":\"DEATHMATCH\",\
\"Current Map\":\"VEGAS JUNKYARD\",\
\"Current Missions\":[\"VEGAS JUNKYARD\",\"VILLA\",\"PRESIDIO\",\"KILL HOUSE\",\"MURDERTOWN\",\"CQB TRAINING\",\"STREETS\",\"THREE KINGDOMS CASINO\",\"IMPORT\/EXPORT;\"],\
\"RoundDuration\":\"3 minutes\"}");
In Javascript you could keep an object or array with initial values and only post those values that are changed.
But in fact, I would do something similar, but in PHP. You can keep the original values in the session and compare the posted values to those initial values to see what has changed. That way, you won't depend on Javascript. Not only may Javascript be disabled, but also, a fast user may theoretically post the form before the Javascript has run. To move this check to PHP eliminates that risk.

Using a Javascript Variable & Sending to JSON

I'm trying to take a URL's hash value, send it through a function, turn that value into an object, but ultimately send the value to JSON. I have the following setup:
function content(cur){
var mycur = $H(cur);
var pars = "p="+mycur.toJSON();
new Ajax.Updater('my_box', 'test.php', {
parameters: pars
});
}
function update(){
if(window.location.hash.length > 0){
content(window.location.hash.substr(1)); // Everything after the '#'
}
}
var curHashVal = window.location.hash;
window.onload = function(){
setInterval(function(){
if(curHashVal != window.location.hash){
update();
curHashVal = window.location.hash;
}
},1);
}
But for some reason, I can't seem to get the right JSON output. It will either return as a very large object (1:"{",2:"k") or not return at all. I doubt that it is impossible to accomplish, but I've exhausted most of the ways I can think of.
Other ways I've tried were "{" + cur + "}" as well as cur.toObject(), however, none seemed to get the job done.
Thanks for the help!
EDIT: As an end result, I'd like the URL (say product:3,confirmed:1) to be returned as {"product":3,"confirmed":1}
A typical implementation of toJSON() needs either an Array or an Object as the top-most element. Sonsomethig like this will probably work:
var pars = {p: myCur};
pars = pars.toJSON();
First of all native JSON support and the toJSONmethod is not available in all browsers. Older browsers like IE 6/7 or Firefox 2/3 do not support it. You should use a JSON library like json2 by Douglas Crockford. Second I would suggest to use the stringify method of the global JSON object instead of the toJSON function. In my tests
JSON.stringify("...")
works just fine.
If anyone is still looking for my answer, here's the solution!
function build_json(str){
var new_str = "{";
var cut = str.split(",");
for(var x=0; x < cut.length; x++){
if(x > 0){new_str = new_str+",";}
var s = cut[x].split(":");
new_str = new_str+"\""+s[0]+"\":\""+s[1]+"\"";
}
return new_str+"}";
}

Categories

Resources