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
Related
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
It seems everyones using Gson to get JSON from a javascript file or just to exchange JSON in Java classes. I'm trying to send a Gson object to a javascript file but I'm not sure how to get the attributes from the Gson object inside my javascript file. I haven't found any tutorial explain something like that. I'd love to see a tutorial somewhere or have someone explain me how I should do this. I haven't used Gson before.
JSON, whose name means JavaScript Object Notation, was designed to be easy to parse in JavaScript.
Historically you could use eval for that but now there's a dedicated function in all browsers : JSON.parse : pass it your JSON string and it will return an object or an array.
Note that many libraries helping you query the server from a script running in a browser will also do the parsing for you so that you don't even have to call JSON.parse.
dystroy is right.
Assuming you have read your GSON/JSON object into a javascript string, JSON.parse will create an object for you.
E.G.:
var myString = '{"firstName":"John","lastName":"Doe","nickName":"Johnny","title":"Mr","emailAddresses":["johndoe#example.com","john#example.com"]}'
var myObject = JSON.parse(myString);
// now we have an object with properties
console.log(myObject.firstName); // logs "John"
console.log(myObject.emailAddresses[1]); // logs "john#example.com"
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.
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.
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