Check what holds in [object Object] in jQuery - javascript

I am using a jQuery plugin which returns the object, for example using the below code.
onSuccess: function(data, status){
alert(data);
}
returns [object Object]
as it is returning the object i would like to know how do i check all the contents that holds inside that object using js alert();
also i would like to know if JS object and JSON are one and the same.
thank you

Use proper debugging tools like Firebug for Firefox or the built in Chrome developer tools. Then you can inspect objects with console.log or console.dir.
alert is not meant for debugging. It can only output strings, which is of limited use as you already noticed.
also i would like to know if JS object and JSON are one and the same.
No, they are not. JSON is a data exchange format, similar to what XML can be used for, whereas a JavaScript object is a data type in JavaScript.
If you are wondering whether JavaScript object literals are JSON, then this answer has to be answered with no as well.
These are object literals
var foo = {foo: "bar"};
var foo = {"foo": "bar"};
whereas JSON can only exist inside strings in JavaScript:
var foo = '{"foo": "bar"}';
and which then has to be parsed into a equivalent JavaScript data type. This is done by parsers such as the built-in JSON or json2.js.
Don't let their similar syntax/structure fool you.

For the first part of your question, check this: How to Loop through plain JavaScript object with objects as members?
And for your second question regarding json and js object: No, json is a string representation of a data structure, read here: http://en.wikipedia.org/wiki/JSON. However, it easy to parse a json to a js object.

Check this .data( key, value ) or .data( obj )
where
key - A string naming the piece of data to set.
value -The new data value; it can be any Javascript type including Array or Object.
obj - An object of key-value pairs of data to update.
OR
You can also use jQuery.each

Related

Printing JSON object from javascript function on glassfish server log

Scenario: Java servlet running on glassfish 4.1/jdk1.8.45. There is a javascript function being read from Database and executed on server side using javax.script.*. When trying to debug this function, it is desired to output some json objects on server log.It is printing [Object object] instead of the actual JSON.Tried using JSON.stringify(), it gives[undefined].
Is there a way to print the actual contents on the json object in this scenario?
Thanks.
JSON.stringify works only javascript objects. It does not work on Java objects. Please make sure that you're calling JSON.stringify on a JavaScript object.
If you do need to make JSON string on a java object, you can use Object.bindProperties extension (https://wiki.openjdk.java.net/display/Nashorn/Nashorn+extensions#Nashornextensions-Object.bindProperties) to bind properties of the Java object to a script object and then call JSON.stringify on the same.
Sample (test) code is here -> http://hg.openjdk.java.net/jdk9/dev/nashorn/file/0de67a63e2c7/test/script/nosecurity/treeapi/utils.js
This script is used to convert a Nashorn AST tree object [a Java object] as friendly JSON object.
If you want to use JSON.stringify and it gives undefined, does it mean JSON is undefined or just the function?
If so, it may be that Nashorn doesn't have it in the box. Maybe try and add it as a polyfill: you can have a look here or here.
If you are dealing with strings in the Nashorn scripting engine then there is a probability they are Java strings rather than javascript strings. The fix is to convert your Java strings to Javascript strings.
// this string does not work with stringify()
var javaString = someMethodReturningAJavaString();
var jsString = new String(javaString);
// now stringify() works:
var myJson = JSON.stringify({'key': jsString});
If typeof(new String(javaString)) returns object rather than string then use new String(javaString).valueOf(). For some values this seems to be the only solution with Mozilla's Rhino js engine.
If you have numbers then you might need to wrap java objects in the the new Number() constructors.
For details on the Nashorn engine have a look at https://docs.oracle.com/javase/8/docs/technotes/guides/scripting/prog_guide/javascript.html

node js - how to represent json file as var?

I'm editing my post because i want to clarify the meaning of a post,
the real question is not about the code i wrote or about equality operator,it's about representing json file in var.
I'll try to ask this again in different way, I need to implement a function in Node js that get json string as parameter, store this json string in a json file and send this json file to other function,
how am I supposed to do that?
other developer ask me to send some function a json file,
or a variable that represent json file?
how am I supposed to do that?
can i represent file in variable in node js or just hold json obj?
var ob1 = require('./test.json');
var ob2 = {"a" : "b"};
var b = (ob1 === ob2)
test.json of course include exactly the same json as in ob2 object.
when i debug this code in intellij it seems that ob1 and ob2 are exactly the same.
both object with same content.
so why do 'b' value is false?
thanks.
You need to be very clear on your terminology and concepts.
A JavaScript object is a native JavaScript type which contains key-value pairs, and has the literal form enclosed in curly brackets such as {a: 1}.
JSON is a string-based representation loosely based on JavaScript literal object syntax, such as the string '{"a": 1}'.
A JSON file is a file (a physical file, with a filename, in the local file system) containing JSON. In node, it may be read in and converted to a JavaScript object using require('foo.json').
A variable is a way to hold any JavaScript type. That could be a JavaScript object, or it could be a string, and that string could be JSON.
A parameter is the part of a function definition which represents something that will be passed in ("formal parameter"), or passed to the function when called.
So
other developer ask me to send some function a json file
I'm not really sure that other developers have asked you to send a "JSON file". If that's really what they meant, you could pass a filename. If you show us the function the developer has asked you pass a "JSON file" to, we would be able to figure out what they really meant.
or a variable that represent json file?
It's more likely that what they asked you to send as a parameter (not a "variable") is either (1) a JavaScript object or, less likely, (2) a JSON string. If they asked you to send a JavaScript object, and you want to send a JavaScript object corresponding to the contents of a JSON file, then you can read in the JSON file with require('foo.json'), and that will read in the file and at the same time convert to a JavaScript object, which you can then just pass.
If they asked you to send "JSON", it's likely they are using incorrect terminology, and actually mean for you to send a JavaScript object, in which case see above.If they really meant "JSON" (meaning a string), then if you have the JSON string already, you could pass that as is; or if you have a JavaScript object, and need to pass it as JSON (for instance, to pass it to an AJAX-like interface), then you could convert the JavaScript object into JSON using JSON.stringify.
In your particular case, you are reading a JSON file and creating a JavaScript object obj1. Then you are creating another JavaScript object using literal object notation obj2. If you want to compare those for deep equality, you can't use == or ===, which compares object identity, and these two objects have distinct identities even if they have the same key/value pairs, so you'll have to use a library which offers deep equality checking, or write your own.
it's about representing json file in var.
I don't know what you mean by saying to "represent" a JSON file in a variable. What you can do, to repeat myself, is to read in the JSON file using require('foo.json') and it will return a JavaScript object you can assign to a variable; or, you can read in the JSON file as text, using standard node file I/O APIs, then convert it a JavaScript object yourself using JSON.parse.
I need to implement a function in Node js that get json string as parameter, store this json string in a json file and send this json file to other function, how am I supposed to do that?
I guess you mean "takes a JSON string as parameter". The most likely interpretation of "send this json file to other function" is actually "pass the corresponding JavaScript object to other function". If that's what you want to do, then
function takeJsonAndSendObject(json) {
otherFunction(JSON.parse(json));
}
If for some reason you really want to "store this json string in a json file", meaning a physical file on your hard disk, then you'll have to use node's file I/O API's to write the physical file. Then you could pass the name of the file to the other function. But why would you do that when you already have the JSON and/or JavaScript object and could pass it directly?
Both objects ob1 and ob2 may have the same content, but they are still two different objects.
obj1 === obj2 does not compare the objects' contents, but their references. These references are not the same, so the comparison has a negative result.
You will have to implement the comparison of the objects' contents yourself, e.g.:
ob1.a === ob2.a
There isn't really a "file" object in Node, but you can send the path to the JSON file as a parameter. Or, even better, send the object itself as a parameter.
There is no file object in NodeJS. If you want to pass a file to another function, pass the path to the file to the function that needs the file. Then from that function, read the file contents using fs module.
Below function accepts a json object, writes it in to a file & returns the path of the file.
function createJSONFile(jsonObject) {
var jsonPath = './jsonFileName.json';
var fs = require('fs');
fs.writeFileSync(jsonPath, JSON.stringify(jsonObject));
return jsonPath;
}
Also, when you read the json data from the file, though the content will be the same, you cannot expect the object that you saved in the json file is same as the one you read. Because, they are two different objects now.
var object = {name: 'test'};
var filePath = createJSONFile(object);
var json = require(filePath);
object === json // false
//to check the equality of the content, you need to use `JSON.stringify`.
JSON.stringify(object) === JSON.stringify(json) // true

why can't I parse JSON without quotes in JS?

Why can't I parse the JSON object? I need to wrap it in quotes for parse to work.
// JSON object
var foo = {"sayHi": {"nl":"hoi", "en":"hello"}};
alert(foo.sayHi.en);
// string
var foo = '{"sayHi": {"nl":"hoi", "en":"hello"}}';
alert(JSON.parse(foo).sayHi.nl);
edit:
// does not work
var foo = {"sayHi": {"nl":"hoi", "en":"hello"}};
alert(JSON.parse(foo).sayHi.nl);
Yes, both work, but the first foo doesn't work the with parse. And I like the first foo better, because I don't need to worry about linebreaks, quotes and plus signs.
edit2:
I'm really looking for a nice way to store the JSON in a variable instead of using an ajax call to get it.
Because this {"sayHi": {"nl":"hoi", "en":"hello"}} is already js object
and this '{"sayHi": {"nl":"hoi", "en":"hello"}}' is just a string, containing whatever, maybe json
Depends on what you mean by "parse the JSON object" (which is not a thing by the way; JSON is a notation). If you want to parse it into an object then congratulations, you're done! JSON.parse takes a string using JSON (the notation) and turns it into an object in JavaScript (but many other languages can also parse JSON and turn it into respective data structures).
Both of your code snippets work as expected, though.

Serialize JavaScript objects

I'm trying to serialize a JavaScript object to json, to be deserialized later back into its original form.
The hard part is that it's not just primitives I need to serialize. For example:
function Foo() {
this.bar = "Hello World";
}
Foo.prototype.baz = function() {
alert(this.bar);
}
var qux = new Foo();
How would I serialize qux? If I simply JSON.stringify then JSON.parse it, I wouldn't be able to call qux.baz().
Are there any standards or tools or techniques out there to do this? Any tips to point me in the right direction?
Thanks.
JavaScript object to JSON
Unfortunately you cannot serialize your complete object to JSON since the JSON spec does not allow functions to be serialized.
You can however create your own serialization standard. You can call it Javascript Frozen Object (JSFO) which is a good name since in other languages what you're trying to do is usually called "freezing". Or if you want a name similar to JSON you can call it Javascript Frozen (or Full?) Object Notation (JSFON).
The implementation is fairly straightforward. You can copy the JSON code from any of the libraries that implement it like jQuery or YUI. Or you can download any of the reference implementation from json.org and modify it to stringify functions as well.
To stringify functions you basically need to do something like this:
if (typeof obj == 'function') {
return '"' + key + '":' + obj.toString();
}
plug something like that into any of the JSON stringification libraries.
But please don't call it JSON since JSON is a very specific data format with a published specification.
I'd start looking at the JSON documentation on MDN, specifically JSON.stringify.

Complex Javascript objects to JSON Objects

Duplicate: Converting HTML TAG Object to JSON Object
Hi,
Is there is any Javascript API that converts complex Javascript Objects To JSON String???
I don't think what you're looking for a an API per se. That would be a something like a service where you send data and receive back something else.
What you want is called a serializer. It turns a javascript object into a string of text representing the object-literal. For example:
var foo = {};
foo[bar] = "baz";
//do serializing to get a -string- that looks like this:
{bar: "baz"}
That way when a service receives this JSON information, if it uses javascript, it's already in a format where it can be read directly into memory without conversion. Here is an example javascript serializer:
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx

Categories

Resources